xref: /linux/fs/smb/server/smb2pdu.c (revision ceaebef91d1aff671a512d5f003766ea41152d94)
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/statfs.h>
13 #include <linux/ethtool.h>
14 #include <linux/falloc.h>
15 #include <linux/mount.h>
16 #include <linux/filelock.h>
17 #include <linux/fileattr.h>
18 
19 #include "glob.h"
20 #include "../common/smbfsctl.h"
21 #include "oplock.h"
22 #include "smbacl.h"
23 
24 #include "auth.h"
25 #include "asn1.h"
26 #include "connection.h"
27 #include "transport_ipc.h"
28 #include "transport_rdma.h"
29 #include "vfs.h"
30 #include "vfs_cache.h"
31 #include "misc.h"
32 
33 #include "server.h"
34 #include "smb_common.h"
35 #include "../common/smb2status.h"
36 #include "ksmbd_work.h"
37 #include "mgmt/user_config.h"
38 #include "mgmt/share_config.h"
39 #include "mgmt/tree_connect.h"
40 #include "mgmt/user_session.h"
41 #include "mgmt/ksmbd_ida.h"
42 #include "ndr.h"
43 #include "stats.h"
44 #include "transport_tcp.h"
45 #include "compress.h"
46 
47 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
48 {
49 	if (work->next_smb2_rcv_hdr_off) {
50 		*req = ksmbd_req_buf_next(work);
51 		*rsp = ksmbd_resp_buf_next(work);
52 	} else {
53 		*req = smb_get_msg(work->request_buf);
54 		*rsp = smb_get_msg(work->response_buf);
55 	}
56 }
57 
58 #define WORK_BUFFERS(w, rq, rs)	__wbuf((w), (void **)&(rq), (void **)&(rs))
59 
60 #define SMB2_CREATE_FILE_ATTRIBUTE_MASK \
61 	(FILE_ATTRIBUTE_MASK & ~(FILE_ATTRIBUTE_INTEGRITY_STREAM | \
62 				 FILE_ATTRIBUTE_NO_SCRUB_DATA))
63 
64 /* Windows reports automatic write-time updates at roughly 15 ms resolution. */
65 #define KSMBD_WRITE_TIME_RESOLUTION	(15ULL * 10000)
66 
67 /**
68  * check_session_id() - check for valid session id in smb header
69  * @conn:	connection instance
70  * @id:		session id from smb header
71  *
72  * Return:      1 if valid session id, otherwise 0
73  */
74 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
75 {
76 	struct ksmbd_session *sess;
77 
78 	if (id == 0 || id == -1)
79 		return false;
80 
81 	sess = ksmbd_session_lookup_all(conn, id);
82 	if (sess) {
83 		ksmbd_user_session_put(sess);
84 		return true;
85 	}
86 	pr_err("Invalid user session id: %llu\n", id);
87 	return false;
88 }
89 
90 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
91 {
92 	struct channel *chann;
93 
94 	down_read(&sess->chann_lock);
95 	chann = xa_load(&sess->ksmbd_chann_list, (long)conn);
96 	up_read(&sess->chann_lock);
97 
98 	return chann;
99 }
100 
101 #define KSMBD_MAX_CHANNELS	32
102 
103 static int register_session_channel(struct ksmbd_session *sess,
104 				    struct ksmbd_conn *conn,
105 				    const char *sess_key)
106 {
107 	struct channel *chann, *old;
108 	unsigned long index;
109 	unsigned int count = 0;
110 	int rc = 0;
111 
112 	down_write(&sess->chann_lock);
113 	if (xa_load(&sess->ksmbd_chann_list, (long)conn))
114 		goto out;
115 
116 	xa_for_each(&sess->ksmbd_chann_list, index, chann)
117 		count++;
118 	if (count >= KSMBD_MAX_CHANNELS) {
119 		rc = -ENOSPC;
120 		goto out;
121 	}
122 
123 	chann = kmalloc_obj(struct channel, KSMBD_DEFAULT_GFP);
124 	if (!chann) {
125 		rc = -ENOMEM;
126 		goto out;
127 	}
128 
129 	chann->conn = conn;
130 	memcpy(chann->sess_key, sess_key, sizeof(chann->sess_key));
131 	old = xa_store(&sess->ksmbd_chann_list, (long)conn, chann,
132 		       KSMBD_DEFAULT_GFP);
133 	if (xa_is_err(old)) {
134 		kfree_sensitive(chann);
135 		rc = xa_err(old);
136 	}
137 out:
138 	up_write(&sess->chann_lock);
139 	return rc;
140 }
141 
142 /**
143  * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
144  * @work:	smb work
145  *
146  * Return:	0 if there is a tree connection matched or these are
147  *		skipable commands, otherwise error
148  */
149 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
150 {
151 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
152 	unsigned int cmd = le16_to_cpu(req_hdr->Command);
153 	unsigned int tree_id;
154 
155 	if (cmd == SMB2_TREE_CONNECT_HE ||
156 	    cmd ==  SMB2_CANCEL_HE ||
157 	    cmd ==  SMB2_LOGOFF_HE) {
158 		ksmbd_debug(SMB, "skip to check tree connect request\n");
159 		return 0;
160 	}
161 
162 	if (xa_empty(&work->sess->tree_conns)) {
163 		ksmbd_debug(SMB, "NO tree connected\n");
164 		return -ENOENT;
165 	}
166 
167 	tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
168 
169 	/*
170 	 * If request is not the first in Compound request,
171 	 * Just validate tree id in header with work->tcon->id.
172 	 */
173 	if (work->next_smb2_rcv_hdr_off) {
174 		if (!work->tcon) {
175 			pr_err("The first operation in the compound does not have tcon\n");
176 			return -EINVAL;
177 		}
178 		if (work->tcon->t_state != TREE_CONNECTED)
179 			return -ENOENT;
180 		if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
181 			pr_err("tree id(%u) is different with id(%u) in first operation\n",
182 					tree_id, work->tcon->id);
183 			return -EINVAL;
184 		}
185 		return 1;
186 	}
187 
188 	work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
189 	if (!work->tcon) {
190 		pr_err("Invalid tid %d\n", tree_id);
191 		return -ENOENT;
192 	}
193 
194 	return 1;
195 }
196 
197 /**
198  * smb2_set_err_rsp() - set error response code on smb response
199  * @work:	smb work containing response buffer
200  */
201 void smb2_set_err_rsp(struct ksmbd_work *work)
202 {
203 	struct smb2_err_rsp *err_rsp;
204 
205 	if (work->next_smb2_rcv_hdr_off)
206 		err_rsp = ksmbd_resp_buf_next(work);
207 	else
208 		err_rsp = smb_get_msg(work->response_buf);
209 
210 	if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
211 		int err;
212 
213 		err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
214 		err_rsp->ErrorContextCount = 0;
215 		err_rsp->Reserved = 0;
216 		err_rsp->ByteCount = 0;
217 		err_rsp->ErrorData[0] = 0;
218 		err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
219 					__SMB2_HEADER_STRUCTURE_SIZE +
220 						SMB2_ERROR_STRUCTURE_SIZE2);
221 		if (err)
222 			work->send_no_response = 1;
223 	}
224 }
225 
226 /**
227  * is_smb2_neg_cmd() - is it smb2 negotiation command
228  * @work:	smb work containing smb header
229  *
230  * Return:      true if smb2 negotiation command, otherwise false
231  */
232 bool is_smb2_neg_cmd(struct ksmbd_work *work)
233 {
234 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
235 
236 	/* is it SMB2 header ? */
237 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
238 		return false;
239 
240 	/* make sure it is request not response message */
241 	if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
242 		return false;
243 
244 	if (hdr->Command != SMB2_NEGOTIATE)
245 		return false;
246 
247 	return true;
248 }
249 
250 /**
251  * is_smb2_rsp() - is it smb2 response
252  * @work:	smb work containing smb response buffer
253  *
254  * Return:      true if smb2 response, otherwise false
255  */
256 bool is_smb2_rsp(struct ksmbd_work *work)
257 {
258 	struct smb2_hdr *hdr = smb_get_msg(work->response_buf);
259 
260 	/* is it SMB2 header ? */
261 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
262 		return false;
263 
264 	/* make sure it is response not request message */
265 	if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
266 		return false;
267 
268 	return true;
269 }
270 
271 /**
272  * get_smb2_cmd_val() - get smb command code from smb header
273  * @work:	smb work containing smb request buffer
274  *
275  * Return:      smb2 request command value
276  */
277 u16 get_smb2_cmd_val(struct ksmbd_work *work)
278 {
279 	struct smb2_hdr *rcv_hdr;
280 
281 	if (work->next_smb2_rcv_hdr_off)
282 		rcv_hdr = ksmbd_req_buf_next(work);
283 	else
284 		rcv_hdr = smb_get_msg(work->request_buf);
285 	return le16_to_cpu(rcv_hdr->Command);
286 }
287 
288 /**
289  * set_smb2_rsp_status() - set error response code on smb2 header
290  * @work:	smb work containing response buffer
291  * @err:	error response code
292  */
293 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
294 {
295 	struct smb2_hdr *rsp_hdr;
296 
297 	if (work->next_smb2_rcv_hdr_off) {
298 		rsp_hdr = ksmbd_resp_buf_next(work);
299 		rsp_hdr->Status = err;
300 		smb2_set_err_rsp(work);
301 		return;
302 	}
303 
304 	rsp_hdr = smb_get_msg(work->response_buf);
305 	rsp_hdr->Status = err;
306 
307 	work->iov_idx = 0;
308 	work->iov_cnt = 0;
309 	work->next_smb2_rcv_hdr_off = 0;
310 	smb2_set_err_rsp(work);
311 }
312 
313 /**
314  * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
315  * @work:	smb work containing smb request buffer
316  *
317  * smb2 negotiate response is sent in reply of smb1 negotiate command for
318  * dialect auto-negotiation.
319  */
320 int init_smb2_neg_rsp(struct ksmbd_work *work)
321 {
322 	struct smb2_hdr *rsp_hdr;
323 	struct smb2_negotiate_rsp *rsp;
324 	struct ksmbd_conn *conn = work->conn;
325 	int err;
326 
327 	rsp_hdr = smb_get_msg(work->response_buf);
328 	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
329 	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
330 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
331 	rsp_hdr->CreditRequest = cpu_to_le16(2);
332 	rsp_hdr->Command = SMB2_NEGOTIATE;
333 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
334 	rsp_hdr->NextCommand = 0;
335 	rsp_hdr->MessageId = 0;
336 	rsp_hdr->Id.SyncId.ProcessId = 0;
337 	rsp_hdr->Id.SyncId.TreeId = 0;
338 	rsp_hdr->SessionId = 0;
339 	memset(rsp_hdr->Signature, 0, 16);
340 
341 	rsp = smb_get_msg(work->response_buf);
342 
343 	WARN_ON(ksmbd_conn_good(conn));
344 
345 	rsp->StructureSize = cpu_to_le16(65);
346 	ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
347 	rsp->DialectRevision = cpu_to_le16(conn->dialect);
348 	/* Not setting conn guid rsp->ServerGUID, as it
349 	 * not used by client for identifying connection
350 	 */
351 	rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
352 	/* Default Max Message Size till SMB2.0, 64K*/
353 	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
354 	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
355 	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
356 
357 	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
358 	rsp->ServerStartTime = 0;
359 
360 	rsp->SecurityBufferOffset = cpu_to_le16(128);
361 	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
362 	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
363 		le16_to_cpu(rsp->SecurityBufferOffset));
364 	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
365 	if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
366 		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
367 	err = ksmbd_iov_pin_rsp(work, rsp,
368 				sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
369 	if (err)
370 		return err;
371 	conn->use_spnego = true;
372 
373 	ksmbd_conn_set_need_negotiate(conn);
374 	return 0;
375 }
376 
377 /**
378  * smb2_set_rsp_credits() - set number of credits in response buffer
379  * @work:	smb work containing smb response buffer
380  */
381 int smb2_set_rsp_credits(struct ksmbd_work *work)
382 {
383 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
384 	struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
385 	struct ksmbd_conn *conn = work->conn;
386 	unsigned short credits_requested, aux_max;
387 	unsigned short credit_charge, credits_granted = 0;
388 
389 	if (work->send_no_response)
390 		return 0;
391 
392 	hdr->CreditCharge = req_hdr->CreditCharge;
393 
394 	if (conn->total_credits > conn->vals->max_credits) {
395 		hdr->CreditRequest = 0;
396 		pr_err("Total credits overflow: %d\n", conn->total_credits);
397 		return -EINVAL;
398 	}
399 
400 	credit_charge = max_t(unsigned short,
401 			      le16_to_cpu(req_hdr->CreditCharge), 1);
402 	if (credit_charge > conn->total_credits) {
403 		ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
404 			    credit_charge, conn->total_credits);
405 		return -EINVAL;
406 	}
407 
408 	conn->total_credits -= credit_charge;
409 	conn->outstanding_credits -= credit_charge;
410 	work->credit_charge = 0;
411 	credits_requested = max_t(unsigned short,
412 				  le16_to_cpu(req_hdr->CreditRequest), 1);
413 
414 	/* according to smb2.credits smbtorture, Windows server
415 	 * 2016 or later grant up to 8192 credits at once.
416 	 *
417 	 * TODO: Need to adjuct CreditRequest value according to
418 	 * current cpu load
419 	 */
420 	if (hdr->Command == SMB2_NEGOTIATE)
421 		aux_max = 1;
422 	else
423 		aux_max = conn->vals->max_credits - conn->total_credits;
424 	credits_granted = min_t(unsigned short, credits_requested, aux_max);
425 
426 	conn->total_credits += credits_granted;
427 	work->credits_granted += credits_granted;
428 
429 	if (!req_hdr->NextCommand) {
430 		/* Update CreditRequest in last request */
431 		hdr->CreditRequest = cpu_to_le16(work->credits_granted);
432 	}
433 	ksmbd_debug(SMB,
434 		    "credits: requested[%d] granted[%d] total_granted[%d]\n",
435 		    credits_requested, credits_granted,
436 		    conn->total_credits);
437 	return 0;
438 }
439 
440 /**
441  * init_chained_smb2_rsp() - initialize smb2 chained response
442  * @work:	smb work containing smb response buffer
443  */
444 static void init_chained_smb2_rsp(struct ksmbd_work *work)
445 {
446 	struct smb2_hdr *req = ksmbd_req_buf_next(work);
447 	struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
448 	struct smb2_hdr *rsp_hdr;
449 	struct smb2_hdr *rcv_hdr;
450 	int next_hdr_offset = 0;
451 	int len, new_len;
452 
453 	/* Len of this response = updated RFC len - offset of previous cmd
454 	 * in the compound rsp
455 	 */
456 
457 	/* Storing the current local FID which may be needed by subsequent
458 	 * command in the compound request
459 	 */
460 	if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
461 		work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
462 		work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
463 		work->compound_sid = le64_to_cpu(rsp->SessionId);
464 		work->compound_status = STATUS_SUCCESS;
465 	} else if ((req->Command == SMB2_FLUSH ||
466 		    req->Command == SMB2_READ ||
467 		    req->Command == SMB2_WRITE) &&
468 		   rsp->Status == STATUS_SUCCESS) {
469 		u64 volatile_id = KSMBD_NO_FID;
470 		u64 persistent_id = KSMBD_NO_FID;
471 
472 		if (req->Command == SMB2_FLUSH) {
473 			struct smb2_flush_req *flush_req =
474 				(struct smb2_flush_req *)req;
475 
476 			volatile_id = flush_req->VolatileFileId;
477 			persistent_id = flush_req->PersistentFileId;
478 		} else if (req->Command == SMB2_READ) {
479 			struct smb2_read_req *read_req =
480 				(struct smb2_read_req *)req;
481 
482 			volatile_id = read_req->VolatileFileId;
483 			persistent_id = read_req->PersistentFileId;
484 		} else {
485 			struct smb2_write_req *write_req =
486 				(struct smb2_write_req *)req;
487 
488 			volatile_id = write_req->VolatileFileId;
489 			persistent_id = write_req->PersistentFileId;
490 		}
491 
492 		if (has_file_id(volatile_id)) {
493 			work->compound_fid = volatile_id;
494 			work->compound_pfid = persistent_id;
495 			work->compound_sid = le64_to_cpu(rsp->SessionId);
496 			work->compound_status = STATUS_SUCCESS;
497 		}
498 	} else if (req->Command == SMB2_CREATE) {
499 		work->compound_fid = KSMBD_NO_FID;
500 		work->compound_pfid = KSMBD_NO_FID;
501 		work->compound_sid = le64_to_cpu(rsp->SessionId);
502 		work->compound_status = rsp->Status;
503 	} else if (rsp->Status != STATUS_SUCCESS) {
504 		work->compound_sid = le64_to_cpu(rsp->SessionId);
505 		/*
506 		 * Only carry the failed status forward when the failing command
507 		 * was itself part of the related chain. An unrelated command
508 		 * that fails (e.g. a standalone request with a bad session id)
509 		 * must not seed the status for a following related command,
510 		 * which has to be evaluated on its own (and may legitimately
511 		 * fail with a different status such as INVALID_PARAMETER). The
512 		 * compound session id is still tracked so a following related
513 		 * command can validate it.
514 		 */
515 		if (req->Flags & SMB2_FLAGS_RELATED_OPERATIONS)
516 			work->compound_status = rsp->Status;
517 	}
518 
519 	len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
520 	next_hdr_offset = le32_to_cpu(req->NextCommand);
521 
522 	new_len = ALIGN(len, 8);
523 	work->iov[work->iov_idx].iov_len += (new_len - len);
524 	inc_rfc1001_len(work->response_buf, new_len - len);
525 	rsp->NextCommand = cpu_to_le32(new_len);
526 
527 	work->next_smb2_rcv_hdr_off += next_hdr_offset;
528 	work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
529 	work->next_smb2_rsp_hdr_off += new_len;
530 	ksmbd_debug(SMB,
531 		    "Compound req new_len = %d rcv off = %d rsp off = %d\n",
532 		    new_len, work->next_smb2_rcv_hdr_off,
533 		    work->next_smb2_rsp_hdr_off);
534 
535 	rsp_hdr = ksmbd_resp_buf_next(work);
536 	rcv_hdr = ksmbd_req_buf_next(work);
537 
538 	if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
539 		ksmbd_debug(SMB, "related flag should be set\n");
540 		work->compound_fid = KSMBD_NO_FID;
541 		work->compound_pfid = KSMBD_NO_FID;
542 		work->compound_status = STATUS_SUCCESS;
543 	}
544 	memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
545 	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
546 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
547 	rsp_hdr->Command = rcv_hdr->Command;
548 
549 	/*
550 	 * Message is response. We don't grant oplock yet.
551 	 */
552 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
553 				SMB2_FLAGS_RELATED_OPERATIONS);
554 	rsp_hdr->NextCommand = 0;
555 	rsp_hdr->MessageId = rcv_hdr->MessageId;
556 	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
557 	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
558 	rsp_hdr->SessionId = rcv_hdr->SessionId;
559 	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
560 }
561 
562 static bool smb2_compound_has_failed(struct ksmbd_work *work,
563 				     struct smb2_hdr *rsp)
564 {
565 	if (!work->next_smb2_rcv_hdr_off ||
566 	    has_file_id(work->compound_fid) ||
567 	    work->compound_status == STATUS_SUCCESS)
568 		return false;
569 
570 	rsp->Status = work->compound_status;
571 	smb2_set_err_rsp(work);
572 	return true;
573 }
574 
575 /**
576  * is_chained_smb2_message() - check for chained command
577  * @work:	smb work containing smb request buffer
578  *
579  * Return:      true if chained request, otherwise false
580  */
581 bool is_chained_smb2_message(struct ksmbd_work *work)
582 {
583 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
584 	unsigned int len, next_cmd;
585 
586 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
587 		return false;
588 
589 	hdr = ksmbd_req_buf_next(work);
590 	next_cmd = le32_to_cpu(hdr->NextCommand);
591 	if (next_cmd > 0) {
592 		if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
593 			__SMB2_HEADER_STRUCTURE_SIZE >
594 		    get_rfc1002_len(work->request_buf)) {
595 			pr_err("next command(%u) offset exceeds smb msg size\n",
596 			       next_cmd);
597 			return false;
598 		}
599 
600 		if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
601 		    work->response_sz) {
602 			pr_err("next response offset exceeds response buffer size\n");
603 			return false;
604 		}
605 
606 		ksmbd_debug(SMB, "got SMB2 chained command\n");
607 		init_chained_smb2_rsp(work);
608 		return true;
609 	} else if (work->next_smb2_rcv_hdr_off) {
610 		/*
611 		 * This is last request in chained command,
612 		 * align response to 8 byte
613 		 */
614 		len = ALIGN(get_rfc1002_len(work->response_buf), 8);
615 		len = len - get_rfc1002_len(work->response_buf);
616 		if (len) {
617 			ksmbd_debug(SMB, "padding len %u\n", len);
618 			work->iov[work->iov_idx].iov_len += len;
619 			inc_rfc1001_len(work->response_buf, len);
620 		}
621 		work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
622 	}
623 	return false;
624 }
625 
626 /**
627  * init_smb2_rsp_hdr() - initialize smb2 response
628  * @work:	smb work containing smb request buffer
629  *
630  * Return:      0
631  */
632 int init_smb2_rsp_hdr(struct ksmbd_work *work)
633 {
634 	struct smb2_hdr *rsp_hdr = smb_get_msg(work->response_buf);
635 	struct smb2_hdr *rcv_hdr = smb_get_msg(work->request_buf);
636 
637 	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
638 	rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
639 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
640 	rsp_hdr->Command = rcv_hdr->Command;
641 
642 	/*
643 	 * Message is response. We don't grant oplock yet.
644 	 */
645 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
646 	rsp_hdr->NextCommand = 0;
647 	rsp_hdr->MessageId = rcv_hdr->MessageId;
648 	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
649 	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
650 	rsp_hdr->SessionId = rcv_hdr->SessionId;
651 	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
652 
653 	return 0;
654 }
655 
656 /**
657  * smb2_allocate_rsp_buf() - allocate smb2 response buffer
658  * @work:	smb work containing smb request buffer
659  *
660  * Return:      0 on success, otherwise error
661  */
662 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
663 {
664 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
665 	size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
666 	size_t large_sz = small_sz + work->conn->vals->max_trans_size;
667 	size_t sz = small_sz;
668 	int cmd = le16_to_cpu(hdr->Command);
669 
670 	if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
671 		sz = large_sz;
672 
673 	if (cmd == SMB2_QUERY_INFO_HE) {
674 		struct smb2_query_info_req *req;
675 
676 		if (get_rfc1002_len(work->request_buf) <
677 		    offsetof(struct smb2_query_info_req, OutputBufferLength))
678 			return -EINVAL;
679 
680 		req = smb_get_msg(work->request_buf);
681 		if ((req->InfoType == SMB2_O_INFO_FILE &&
682 		     (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
683 		     req->FileInfoClass == FILE_ALL_INFORMATION)) ||
684 		    req->InfoType == SMB2_O_INFO_SECURITY)
685 			sz = large_sz;
686 	}
687 
688 	/* allocate large response buf for chained commands */
689 	if (le32_to_cpu(hdr->NextCommand) > 0)
690 		sz = large_sz;
691 
692 	work->response_buf = kvzalloc(sz, KSMBD_DEFAULT_GFP);
693 	if (!work->response_buf)
694 		return -ENOMEM;
695 
696 	work->response_sz = sz;
697 	return 0;
698 }
699 
700 /**
701  * smb2_check_user_session() - check for valid session for a user
702  * @work:	smb work containing smb request buffer
703  *
704  * Return:      0 on success, otherwise error
705  */
706 int smb2_check_user_session(struct ksmbd_work *work)
707 {
708 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
709 	struct ksmbd_conn *conn = work->conn;
710 	unsigned int cmd = le16_to_cpu(req_hdr->Command);
711 	unsigned long long sess_id;
712 
713 	/*
714 	 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
715 	 * require a session id, so no need to validate user session's for
716 	 * these commands.
717 	 */
718 	if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
719 	    cmd == SMB2_SESSION_SETUP_HE)
720 		return 0;
721 
722 	if (!ksmbd_conn_good(conn))
723 		return -EIO;
724 
725 	sess_id = le64_to_cpu(req_hdr->SessionId);
726 
727 	/*
728 	 * If request is not the first in Compound request,
729 	 * Just validate session id in header with work->sess->id.
730 	 */
731 	if (work->next_smb2_rcv_hdr_off) {
732 		if (!work->sess) {
733 			pr_err("The first operation in the compound does not have sess\n");
734 			return -EINVAL;
735 		}
736 		if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
737 			pr_err("session id(%llu) is different with the first operation(%lld)\n",
738 					sess_id, work->sess->id);
739 			return -EINVAL;
740 		}
741 		if (work->sess->state != SMB2_SESSION_VALID) {
742 			pr_err("compound request on a non-valid session (state %d)\n",
743 					work->sess->state);
744 			return -EINVAL;
745 		}
746 		return 1;
747 	}
748 
749 	/* Check for validity of user session */
750 	work->sess = ksmbd_session_lookup_all(conn, sess_id);
751 	if (work->sess)
752 		return 1;
753 	ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
754 	return -ENOENT;
755 }
756 
757 /**
758  * smb2_get_name() - get filename string from on the wire smb format
759  * @src:	source buffer
760  * @maxlen:	maxlen of source string
761  * @local_nls:	nls_table pointer
762  *
763  * Return:      matching converted filename on success, otherwise error ptr
764  */
765 static char *
766 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
767 {
768 	char *name;
769 
770 	name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
771 	if (IS_ERR(name)) {
772 		pr_err("failed to get name %ld\n", PTR_ERR(name));
773 		return name;
774 	}
775 
776 	if (*name == '\0') {
777 		kfree(name);
778 		return ERR_PTR(-EINVAL);
779 	}
780 
781 	if (*name == '\\') {
782 		pr_err("not allow directory name included leading slash\n");
783 		kfree(name);
784 		return ERR_PTR(-EINVAL);
785 	}
786 
787 	ksmbd_conv_path_to_unix(name);
788 	ksmbd_strip_last_slash(name);
789 	return name;
790 }
791 
792 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
793 {
794 	struct ksmbd_conn *conn = work->conn;
795 	int id;
796 
797 	id = ksmbd_acquire_async_msg_id(&conn->async_ida);
798 	if (id < 0) {
799 		pr_err("Failed to alloc async message id\n");
800 		return id;
801 	}
802 	work->asynchronous = true;
803 	work->async_id = id;
804 
805 	ksmbd_debug(SMB,
806 		    "Send interim Response to inform async request id : %d\n",
807 		    work->async_id);
808 
809 	work->cancel_fn = fn;
810 	work->cancel_argv = arg;
811 
812 	if (list_empty(&work->async_request_entry)) {
813 		spin_lock(&conn->request_lock);
814 		list_add_tail(&work->async_request_entry, &conn->async_requests);
815 		spin_unlock(&conn->request_lock);
816 	}
817 
818 	return 0;
819 }
820 
821 void release_async_work(struct ksmbd_work *work)
822 {
823 	struct ksmbd_conn *conn = work->conn;
824 
825 	spin_lock(&conn->request_lock);
826 	list_del_init(&work->async_request_entry);
827 	spin_unlock(&conn->request_lock);
828 
829 	work->asynchronous = 0;
830 	work->cancel_fn = NULL;
831 	kfree(work->cancel_argv);
832 	work->cancel_argv = NULL;
833 	if (work->async_id) {
834 		ksmbd_release_id(&conn->async_ida, work->async_id);
835 		work->async_id = 0;
836 	}
837 }
838 
839 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
840 {
841 	struct smb2_hdr *rsp_hdr;
842 	struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
843 
844 	if (!in_work)
845 		return;
846 
847 	if (allocate_interim_rsp_buf(in_work)) {
848 		pr_err("smb_allocate_rsp_buf failed!\n");
849 		ksmbd_free_work_struct(in_work);
850 		return;
851 	}
852 
853 	in_work->conn = work->conn;
854 	memcpy(smb_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
855 	       __SMB2_HEADER_STRUCTURE_SIZE);
856 
857 	rsp_hdr = smb_get_msg(in_work->response_buf);
858 	rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
859 	rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
860 	smb2_set_err_rsp(in_work);
861 	rsp_hdr->Status = status;
862 
863 	ksmbd_conn_write(in_work);
864 	ksmbd_free_work_struct(in_work);
865 }
866 
867 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
868 {
869 	if (S_ISDIR(mode) || S_ISREG(mode))
870 		return 0;
871 
872 	if (S_ISLNK(mode))
873 		return IO_REPARSE_TAG_LX_SYMLINK_LE;
874 	else if (S_ISFIFO(mode))
875 		return IO_REPARSE_TAG_LX_FIFO_LE;
876 	else if (S_ISSOCK(mode))
877 		return IO_REPARSE_TAG_AF_UNIX_LE;
878 	else if (S_ISCHR(mode))
879 		return IO_REPARSE_TAG_LX_CHR_LE;
880 	else if (S_ISBLK(mode))
881 		return IO_REPARSE_TAG_LX_BLK_LE;
882 
883 	return 0;
884 }
885 
886 /**
887  * smb2_get_dos_mode() - get file mode in dos format from unix mode
888  * @stat:	kstat containing file mode
889  * @attribute:	attribute flags
890  *
891  * Return:      converted dos mode
892  */
893 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
894 {
895 	int attr = 0;
896 
897 	if (S_ISDIR(stat->mode)) {
898 		attr = FILE_ATTRIBUTE_DIRECTORY |
899 			(attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
900 	} else {
901 		attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
902 		attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
903 		if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
904 				FILE_SUPPORTS_SPARSE_FILES))
905 			attr |= FILE_ATTRIBUTE_SPARSE_FILE;
906 
907 		if (smb2_get_reparse_tag_special_file(stat->mode))
908 			attr |= FILE_ATTRIBUTE_REPARSE_POINT;
909 	}
910 
911 	return attr;
912 }
913 
914 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
915 			       __le16 hash_id)
916 {
917 	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
918 	pneg_ctxt->DataLength = cpu_to_le16(38);
919 	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
920 	pneg_ctxt->Reserved = cpu_to_le32(0);
921 	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
922 	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
923 	pneg_ctxt->HashAlgorithms = hash_id;
924 }
925 
926 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
927 			       __le16 cipher_type)
928 {
929 	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
930 	pneg_ctxt->DataLength = cpu_to_le16(4);
931 	pneg_ctxt->Reserved = cpu_to_le32(0);
932 	pneg_ctxt->CipherCount = cpu_to_le16(1);
933 	pneg_ctxt->Ciphers[0] = cipher_type;
934 }
935 
936 static void build_compress_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
937 				__le16 compress_algorithm, bool compress_chained,
938 				bool compress_pattern)
939 {
940 	/*
941 	 * Return only algorithms implemented by ksmbd. Pattern_V1 is advertised
942 	 * as a second ID when the client also enabled chained transforms.
943 	 */
944 	pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
945 	pneg_ctxt->DataLength = cpu_to_le16(compress_pattern ? 12 : 10);
946 	pneg_ctxt->Reserved = cpu_to_le32(0);
947 	pneg_ctxt->CompressionAlgorithmCount =
948 		cpu_to_le16(compress_pattern ? 2 : 1);
949 	pneg_ctxt->Padding = cpu_to_le16(0);
950 	pneg_ctxt->Flags = compress_chained ?
951 		SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED :
952 		SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE;
953 	pneg_ctxt->CompressionAlgorithms[0] = compress_algorithm;
954 	pneg_ctxt->CompressionAlgorithms[1] = compress_pattern ?
955 		SMB3_COMPRESS_PATTERN : 0;
956 	pneg_ctxt->CompressionAlgorithms[2] = 0;
957 	pneg_ctxt->CompressionAlgorithms[3] = 0;
958 }
959 
960 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
961 				__le16 sign_algo)
962 {
963 	pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
964 	pneg_ctxt->DataLength =
965 		cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
966 			- sizeof(struct smb2_neg_context));
967 	pneg_ctxt->Reserved = cpu_to_le32(0);
968 	pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
969 	pneg_ctxt->SigningAlgorithms[0] = sign_algo;
970 }
971 
972 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
973 {
974 	pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
975 	pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
976 	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
977 	pneg_ctxt->Name[0] = 0x93;
978 	pneg_ctxt->Name[1] = 0xAD;
979 	pneg_ctxt->Name[2] = 0x25;
980 	pneg_ctxt->Name[3] = 0x50;
981 	pneg_ctxt->Name[4] = 0x9C;
982 	pneg_ctxt->Name[5] = 0xB4;
983 	pneg_ctxt->Name[6] = 0x11;
984 	pneg_ctxt->Name[7] = 0xE7;
985 	pneg_ctxt->Name[8] = 0xB4;
986 	pneg_ctxt->Name[9] = 0x23;
987 	pneg_ctxt->Name[10] = 0x83;
988 	pneg_ctxt->Name[11] = 0xDE;
989 	pneg_ctxt->Name[12] = 0x96;
990 	pneg_ctxt->Name[13] = 0x8B;
991 	pneg_ctxt->Name[14] = 0xCD;
992 	pneg_ctxt->Name[15] = 0x7C;
993 }
994 
995 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
996 				  struct smb2_negotiate_rsp *rsp)
997 {
998 	char * const pneg_ctxt = (char *)rsp +
999 			le32_to_cpu(rsp->NegotiateContextOffset);
1000 	int neg_ctxt_cnt = 1;
1001 	int ctxt_size;
1002 
1003 	ksmbd_debug(SMB,
1004 		    "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1005 	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
1006 			   conn->preauth_info->Preauth_HashId);
1007 	ctxt_size = sizeof(struct smb2_preauth_neg_context);
1008 
1009 	if (conn->cipher_type) {
1010 		/* Round to 8 byte boundary */
1011 		ctxt_size = round_up(ctxt_size, 8);
1012 		ksmbd_debug(SMB,
1013 			    "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1014 		build_encrypt_ctxt((struct smb2_encryption_neg_context *)
1015 				   (pneg_ctxt + ctxt_size),
1016 				   conn->cipher_type);
1017 		neg_ctxt_cnt++;
1018 		ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
1019 	}
1020 
1021 	if (conn->compress_algorithm != SMB3_COMPRESS_NONE) {
1022 		ctxt_size = round_up(ctxt_size, 8);
1023 		ksmbd_debug(SMB,
1024 			    "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
1025 		build_compress_ctxt((struct smb2_compression_capabilities_context *)
1026 				    (pneg_ctxt + ctxt_size),
1027 				    conn->compress_algorithm,
1028 				    conn->compress_chained,
1029 				    conn->compress_pattern);
1030 		neg_ctxt_cnt++;
1031 		ctxt_size += sizeof(struct smb2_neg_context) +
1032 			(conn->compress_pattern ? 12 : 10);
1033 	}
1034 
1035 	if (conn->posix_ext_supported) {
1036 		ctxt_size = round_up(ctxt_size, 8);
1037 		ksmbd_debug(SMB,
1038 			    "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1039 		build_posix_ctxt((struct smb2_posix_neg_context *)
1040 				 (pneg_ctxt + ctxt_size));
1041 		neg_ctxt_cnt++;
1042 		ctxt_size += sizeof(struct smb2_posix_neg_context);
1043 	}
1044 
1045 	if (conn->signing_negotiated) {
1046 		ctxt_size = round_up(ctxt_size, 8);
1047 		ksmbd_debug(SMB,
1048 			    "assemble SMB2_SIGNING_CAPABILITIES context\n");
1049 		build_sign_cap_ctxt((struct smb2_signing_capabilities *)
1050 				    (pneg_ctxt + ctxt_size),
1051 				    conn->signing_algorithm);
1052 		neg_ctxt_cnt++;
1053 		ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
1054 	}
1055 
1056 	rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
1057 	return ctxt_size + AUTH_GSS_PADDING;
1058 }
1059 
1060 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
1061 				  struct smb2_preauth_neg_context *pneg_ctxt,
1062 				  int ctxt_len)
1063 {
1064 	/*
1065 	 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
1066 	 * which may not be present. Only check for used HashAlgorithms[1].
1067 	 */
1068 	if (ctxt_len <
1069 	    sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
1070 		return STATUS_INVALID_PARAMETER;
1071 
1072 	if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
1073 		return STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
1074 
1075 	conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
1076 	return STATUS_SUCCESS;
1077 }
1078 
1079 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
1080 				struct smb2_encryption_neg_context *pneg_ctxt,
1081 				int ctxt_len)
1082 {
1083 	int cph_cnt;
1084 	int i, cphs_size;
1085 
1086 	if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
1087 		pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
1088 		return;
1089 	}
1090 
1091 	conn->cipher_type = 0;
1092 
1093 	cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
1094 	cphs_size = cph_cnt * sizeof(__le16);
1095 
1096 	if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
1097 	    ctxt_len) {
1098 		pr_err("Invalid cipher count(%d)\n", cph_cnt);
1099 		return;
1100 	}
1101 
1102 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
1103 		return;
1104 
1105 	for (i = 0; i < cph_cnt; i++) {
1106 		if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
1107 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
1108 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
1109 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
1110 			ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
1111 				    pneg_ctxt->Ciphers[i]);
1112 			conn->cipher_type = pneg_ctxt->Ciphers[i];
1113 			break;
1114 		}
1115 	}
1116 }
1117 
1118 /**
1119  * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
1120  * @conn:	smb connection
1121  *
1122  * Return:	true if connection should be encrypted, else false
1123  */
1124 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
1125 {
1126 	if (!conn->ops->generate_encryptionkey)
1127 		return false;
1128 
1129 	/*
1130 	 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
1131 	 * SMB 3.1.1 uses the cipher_type field.
1132 	 */
1133 	return (conn->vals->req_capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
1134 	    conn->cipher_type;
1135 }
1136 
1137 static __le32 decode_compress_ctxt(struct ksmbd_conn *conn,
1138 				   struct smb2_compression_capabilities_context *pneg_ctxt,
1139 				   int ctxt_len)
1140 {
1141 	int alg_cnt, algs_size, i;
1142 	__le16 *algs;
1143 
1144 	if (sizeof(struct smb2_neg_context) + 10 > ctxt_len) {
1145 		pr_err("Invalid SMB2_COMPRESSION_CAPABILITIES context length\n");
1146 		return STATUS_INVALID_PARAMETER;
1147 	}
1148 
1149 	conn->compress_algorithm = SMB3_COMPRESS_NONE;
1150 	conn->compress_chained = false;
1151 	conn->compress_pattern = false;
1152 
1153 	alg_cnt = le16_to_cpu(pneg_ctxt->CompressionAlgorithmCount);
1154 	if (!alg_cnt)
1155 		return STATUS_INVALID_PARAMETER;
1156 
1157 	if (pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE &&
1158 	    pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED)
1159 		return STATUS_INVALID_PARAMETER;
1160 
1161 	algs_size = alg_cnt * sizeof(__le16);
1162 	if (sizeof(struct smb2_neg_context) + 8 + algs_size > ctxt_len) {
1163 		pr_err("Invalid compression algorithm count(%d)\n", alg_cnt);
1164 		return STATUS_INVALID_PARAMETER;
1165 	}
1166 
1167 	/*
1168 	 * CompressionAlgorithms[] is declared as a fixed 4-element array, but
1169 	 * the actual element count is variable (clients such as Windows may
1170 	 * advertise more). The on-wire length was validated above, so walk the
1171 	 * algorithms through a pointer to avoid a fixed-array bounds check.
1172 	 */
1173 	algs = pneg_ctxt->CompressionAlgorithms;
1174 	for (i = 0; i < alg_cnt; i++) {
1175 		__le16 alg = algs[i];
1176 
1177 		/*
1178 		 * LZ77 is the required general-purpose codec. Pattern_V1 is an
1179 		 * optional chained payload type and cannot stand alone.
1180 		 */
1181 		if (alg == SMB3_COMPRESS_LZ77) {
1182 			conn->compress_algorithm = alg;
1183 			conn->compress_chained =
1184 				pneg_ctxt->Flags ==
1185 				SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED;
1186 			ksmbd_debug(SMB, "Compression Algorithm ID = 0x%x\n",
1187 				    le16_to_cpu(alg));
1188 		} else if (alg == SMB3_COMPRESS_PATTERN) {
1189 			conn->compress_pattern = true;
1190 		}
1191 	}
1192 
1193 	if (conn->compress_algorithm == SMB3_COMPRESS_NONE ||
1194 	    !conn->compress_chained)
1195 		conn->compress_pattern = false;
1196 
1197 	return STATUS_SUCCESS;
1198 }
1199 
1200 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
1201 				 struct smb2_signing_capabilities *pneg_ctxt,
1202 				 int ctxt_len)
1203 {
1204 	int sign_algo_cnt;
1205 	int i, sign_alos_size;
1206 
1207 	if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
1208 		pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
1209 		return;
1210 	}
1211 
1212 	conn->signing_negotiated = false;
1213 	sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
1214 	sign_alos_size = sign_algo_cnt * sizeof(__le16);
1215 
1216 	if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
1217 	    ctxt_len) {
1218 		pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
1219 		return;
1220 	}
1221 
1222 	for (i = 0; i < sign_algo_cnt; i++) {
1223 		if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
1224 		    pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
1225 			ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
1226 				    pneg_ctxt->SigningAlgorithms[i]);
1227 			conn->signing_negotiated = true;
1228 			conn->signing_algorithm =
1229 				pneg_ctxt->SigningAlgorithms[i];
1230 			break;
1231 		}
1232 	}
1233 }
1234 
1235 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
1236 				      struct smb2_negotiate_req *req,
1237 				      unsigned int len_of_smb)
1238 {
1239 	/* +4 is to account for the RFC1001 len field */
1240 	struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
1241 	int i = 0, len_of_ctxts;
1242 	unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
1243 	unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
1244 	__le32 status = STATUS_INVALID_PARAMETER;
1245 	int compress_ctxt_cnt = 0;
1246 
1247 	ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
1248 	if (len_of_smb <= offset) {
1249 		ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1250 		return status;
1251 	}
1252 
1253 	len_of_ctxts = len_of_smb - offset;
1254 
1255 	while (i++ < neg_ctxt_cnt) {
1256 		int clen, ctxt_len;
1257 
1258 		if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1259 			break;
1260 
1261 		pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1262 		clen = le16_to_cpu(pctx->DataLength);
1263 		ctxt_len = clen + sizeof(struct smb2_neg_context);
1264 
1265 		if (ctxt_len > len_of_ctxts)
1266 			break;
1267 
1268 		if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1269 			ksmbd_debug(SMB,
1270 				    "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1271 			if (conn->preauth_info->Preauth_HashId)
1272 				break;
1273 
1274 			status = decode_preauth_ctxt(conn,
1275 						     (struct smb2_preauth_neg_context *)pctx,
1276 						     ctxt_len);
1277 			if (status != STATUS_SUCCESS)
1278 				break;
1279 		} else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1280 			ksmbd_debug(SMB,
1281 				    "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1282 			if (conn->cipher_type)
1283 				break;
1284 
1285 			decode_encrypt_ctxt(conn,
1286 					    (struct smb2_encryption_neg_context *)pctx,
1287 					    ctxt_len);
1288 		} else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1289 			ksmbd_debug(SMB,
1290 				    "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1291 			if (compress_ctxt_cnt++) {
1292 				status = STATUS_INVALID_PARAMETER;
1293 				break;
1294 			}
1295 
1296 			status = decode_compress_ctxt(conn,
1297 				(struct smb2_compression_capabilities_context *)
1298 				pctx, ctxt_len);
1299 			if (status != STATUS_SUCCESS)
1300 				break;
1301 		} else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1302 			ksmbd_debug(SMB,
1303 				    "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1304 		} else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1305 			ksmbd_debug(SMB,
1306 				    "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1307 			conn->posix_ext_supported = true;
1308 		} else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1309 			ksmbd_debug(SMB,
1310 				    "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1311 
1312 			decode_sign_cap_ctxt(conn,
1313 					     (struct smb2_signing_capabilities *)pctx,
1314 					     ctxt_len);
1315 		}
1316 
1317 		/* offsets must be 8 byte aligned */
1318 		offset = (ctxt_len + 7) & ~0x7;
1319 		len_of_ctxts -= offset;
1320 	}
1321 	return status;
1322 }
1323 
1324 /**
1325  * smb2_handle_negotiate() - handler for smb2 negotiate command
1326  * @work:	smb work containing smb request buffer
1327  *
1328  * The caller holds conn->srv_mutex.
1329  *
1330  * Return:      0
1331  */
1332 int smb2_handle_negotiate(struct ksmbd_work *work)
1333 {
1334 	struct ksmbd_conn *conn = work->conn;
1335 	struct smb2_negotiate_req *req = smb_get_msg(work->request_buf);
1336 	struct smb2_negotiate_rsp *rsp = smb_get_msg(work->response_buf);
1337 	int rc = 0;
1338 	unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1339 	__le32 status;
1340 
1341 	ksmbd_debug(SMB, "Received negotiate request\n");
1342 	conn->need_neg = false;
1343 	smb2_buf_len = get_rfc1002_len(work->request_buf);
1344 	smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1345 	if (smb2_neg_size > smb2_buf_len) {
1346 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1347 		rc = -EINVAL;
1348 		goto err_out;
1349 	}
1350 
1351 	if (req->DialectCount == 0) {
1352 		pr_err("malformed packet\n");
1353 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1354 		rc = -EINVAL;
1355 		goto err_out;
1356 	}
1357 
1358 	if (conn->dialect == SMB311_PROT_ID) {
1359 		unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1360 
1361 		if (smb2_buf_len < nego_ctxt_off) {
1362 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1363 			rc = -EINVAL;
1364 			goto err_out;
1365 		}
1366 
1367 		if (smb2_neg_size > nego_ctxt_off) {
1368 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1369 			rc = -EINVAL;
1370 			goto err_out;
1371 		}
1372 
1373 		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1374 		    nego_ctxt_off) {
1375 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1376 			rc = -EINVAL;
1377 			goto err_out;
1378 		}
1379 	} else {
1380 		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1381 		    smb2_buf_len) {
1382 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1383 			rc = -EINVAL;
1384 			goto err_out;
1385 		}
1386 	}
1387 
1388 	conn->cli_cap = le32_to_cpu(req->Capabilities);
1389 	switch (conn->dialect) {
1390 	case SMB311_PROT_ID:
1391 		conn->preauth_info =
1392 			kzalloc_obj(struct preauth_integrity_info,
1393 				    KSMBD_DEFAULT_GFP);
1394 		if (!conn->preauth_info) {
1395 			rc = -ENOMEM;
1396 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1397 			goto err_out;
1398 		}
1399 
1400 		status = deassemble_neg_contexts(conn, req,
1401 						 get_rfc1002_len(work->request_buf));
1402 		if (status != STATUS_SUCCESS) {
1403 			pr_err("deassemble_neg_contexts error(0x%x)\n",
1404 			       status);
1405 			rsp->hdr.Status = status;
1406 			rc = -EINVAL;
1407 			kfree(conn->preauth_info);
1408 			conn->preauth_info = NULL;
1409 			goto err_out;
1410 		}
1411 
1412 		rc = init_smb3_11_server(conn);
1413 		if (rc < 0) {
1414 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1415 			kfree(conn->preauth_info);
1416 			conn->preauth_info = NULL;
1417 			goto err_out;
1418 		}
1419 
1420 		ksmbd_gen_preauth_integrity_hash(conn,
1421 						 work->request_buf,
1422 						 conn->preauth_info->Preauth_HashValue);
1423 		rsp->NegotiateContextOffset =
1424 				cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1425 		neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1426 		break;
1427 	case SMB302_PROT_ID:
1428 		init_smb3_02_server(conn);
1429 		break;
1430 	case SMB30_PROT_ID:
1431 		init_smb3_0_server(conn);
1432 		break;
1433 	case SMB21_PROT_ID:
1434 		init_smb2_1_server(conn);
1435 		break;
1436 	case SMB2X_PROT_ID:
1437 	case BAD_PROT_ID:
1438 	default:
1439 		ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1440 			    conn->dialect);
1441 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1442 		rc = -EINVAL;
1443 		goto err_out;
1444 	}
1445 	rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
1446 
1447 	/* For stats */
1448 	conn->connection_type = conn->dialect;
1449 
1450 	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1451 	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1452 	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1453 
1454 	memcpy(conn->ClientGUID, req->ClientGUID,
1455 			SMB2_CLIENT_GUID_SIZE);
1456 	conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1457 
1458 	rsp->StructureSize = cpu_to_le16(65);
1459 	rsp->DialectRevision = cpu_to_le16(conn->dialect);
1460 	/* Not setting conn guid rsp->ServerGUID, as it
1461 	 * not used by client for identifying server
1462 	 */
1463 	memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1464 
1465 	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1466 	rsp->ServerStartTime = 0;
1467 	ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1468 		    le32_to_cpu(rsp->NegotiateContextOffset),
1469 		    le16_to_cpu(rsp->NegotiateContextCount));
1470 
1471 	rsp->SecurityBufferOffset = cpu_to_le16(128);
1472 	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1473 	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1474 				  le16_to_cpu(rsp->SecurityBufferOffset));
1475 
1476 	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1477 	conn->use_spnego = true;
1478 
1479 	if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1480 	     server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1481 	    req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1482 		conn->sign = true;
1483 	else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1484 		server_conf.enforced_signing = true;
1485 		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1486 		conn->sign = true;
1487 	}
1488 
1489 	conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1490 	ksmbd_conn_set_need_setup(conn);
1491 
1492 err_out:
1493 	if (rc)
1494 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1495 
1496 	if (!rc)
1497 		rc = ksmbd_iov_pin_rsp(work, rsp,
1498 				       sizeof(struct smb2_negotiate_rsp) +
1499 					AUTH_GSS_LENGTH + neg_ctxt_len);
1500 	if (rc < 0)
1501 		smb2_set_err_rsp(work);
1502 	return rc;
1503 }
1504 
1505 static int alloc_preauth_hash(struct ksmbd_session *sess,
1506 			      struct ksmbd_conn *conn)
1507 {
1508 	if (sess->Preauth_HashValue)
1509 		return 0;
1510 
1511 	if (!conn->preauth_info)
1512 		return -ENOMEM;
1513 
1514 	sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1515 					  PREAUTH_HASHVALUE_SIZE, KSMBD_DEFAULT_GFP);
1516 	if (!sess->Preauth_HashValue)
1517 		return -ENOMEM;
1518 
1519 	return 0;
1520 }
1521 
1522 static int generate_preauth_hash(struct ksmbd_work *work)
1523 {
1524 	struct ksmbd_conn *conn = work->conn;
1525 	struct ksmbd_session *sess = work->sess;
1526 	u8 *preauth_hash;
1527 
1528 	if (conn->dialect != SMB311_PROT_ID)
1529 		return 0;
1530 
1531 	if (conn->binding) {
1532 		struct preauth_session *preauth_sess;
1533 
1534 		preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1535 		if (!preauth_sess) {
1536 			preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1537 			if (!preauth_sess)
1538 				return -ENOMEM;
1539 		}
1540 
1541 		preauth_hash = preauth_sess->Preauth_HashValue;
1542 	} else {
1543 		if (!sess->Preauth_HashValue)
1544 			if (alloc_preauth_hash(sess, conn))
1545 				return -ENOMEM;
1546 		preauth_hash = sess->Preauth_HashValue;
1547 	}
1548 
1549 	ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1550 	return 0;
1551 }
1552 
1553 static int decode_negotiation_token(struct ksmbd_conn *conn,
1554 				    struct negotiate_message *negblob,
1555 				    size_t sz)
1556 {
1557 	if (!conn->use_spnego)
1558 		return -EINVAL;
1559 
1560 	if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1561 		if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1562 			conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1563 			conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1564 			conn->use_spnego = false;
1565 		}
1566 	}
1567 	return 0;
1568 }
1569 
1570 static int ntlm_negotiate(struct ksmbd_work *work,
1571 			  struct negotiate_message *negblob,
1572 			  size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
1573 {
1574 	struct challenge_message *chgblob;
1575 	unsigned char *spnego_blob = NULL;
1576 	u16 spnego_blob_len;
1577 	char *neg_blob;
1578 	int sz, rc;
1579 
1580 	ksmbd_debug(SMB, "negotiate phase\n");
1581 	rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1582 	if (rc)
1583 		return rc;
1584 
1585 	sz = le16_to_cpu(rsp->SecurityBufferOffset);
1586 	chgblob = (struct challenge_message *)rsp->Buffer;
1587 	memset(chgblob, 0, sizeof(struct challenge_message));
1588 
1589 	if (!work->conn->use_spnego) {
1590 		sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1591 		if (sz < 0)
1592 			return -ENOMEM;
1593 
1594 		rsp->SecurityBufferLength = cpu_to_le16(sz);
1595 		return 0;
1596 	}
1597 
1598 	sz = sizeof(struct challenge_message);
1599 	sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1600 
1601 	neg_blob = kzalloc(sz, KSMBD_DEFAULT_GFP);
1602 	if (!neg_blob)
1603 		return -ENOMEM;
1604 
1605 	chgblob = (struct challenge_message *)neg_blob;
1606 	sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1607 	if (sz < 0) {
1608 		rc = -ENOMEM;
1609 		goto out;
1610 	}
1611 
1612 	rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1613 					   neg_blob, sz);
1614 	if (rc) {
1615 		rc = -ENOMEM;
1616 		goto out;
1617 	}
1618 
1619 	memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
1620 	rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1621 
1622 out:
1623 	kfree(spnego_blob);
1624 	kfree(neg_blob);
1625 	return rc;
1626 }
1627 
1628 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1629 						  struct smb2_sess_setup_req *req)
1630 {
1631 	int sz;
1632 
1633 	if (conn->use_spnego && conn->mechToken)
1634 		return (struct authenticate_message *)conn->mechToken;
1635 
1636 	sz = le16_to_cpu(req->SecurityBufferOffset);
1637 	return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1638 					       + sz);
1639 }
1640 
1641 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1642 				       struct smb2_sess_setup_req *req)
1643 {
1644 	struct authenticate_message *authblob;
1645 	struct ksmbd_user *user;
1646 	char *name;
1647 	unsigned int name_off, name_len, secbuf_len;
1648 
1649 	if (conn->use_spnego && conn->mechToken)
1650 		secbuf_len = conn->mechTokenLen;
1651 	else
1652 		secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1653 	if (secbuf_len < sizeof(struct authenticate_message)) {
1654 		ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1655 		return NULL;
1656 	}
1657 	authblob = user_authblob(conn, req);
1658 	name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1659 	name_len = le16_to_cpu(authblob->UserName.Length);
1660 
1661 	if (secbuf_len < (u64)name_off + name_len)
1662 		return NULL;
1663 
1664 	name = smb_strndup_from_utf16((const char *)authblob + name_off,
1665 				      name_len,
1666 				      true,
1667 				      conn->local_nls);
1668 	if (IS_ERR(name)) {
1669 		pr_err("cannot allocate memory\n");
1670 		return NULL;
1671 	}
1672 
1673 	ksmbd_debug(SMB, "session setup request for user %s\n", name);
1674 	user = ksmbd_login_user(name);
1675 	kfree(name);
1676 	return user;
1677 }
1678 
1679 static int ntlm_authenticate(struct ksmbd_work *work,
1680 			     struct smb2_sess_setup_req *req,
1681 			     struct smb2_sess_setup_rsp *rsp)
1682 {
1683 	struct ksmbd_conn *conn = work->conn;
1684 	struct ksmbd_session *sess = work->sess;
1685 	struct ksmbd_user *user;
1686 	char channel_key[CIFS_KEY_SIZE] = {};
1687 	char *auth_key = conn->binding ? channel_key : sess->sess_key;
1688 	u64 prev_id;
1689 	bool binding = conn->binding;
1690 	int sz, rc;
1691 
1692 	ksmbd_debug(SMB, "authenticate phase\n");
1693 	if (conn->use_spnego) {
1694 		unsigned char *spnego_blob;
1695 		u16 spnego_blob_len;
1696 
1697 		rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1698 						    &spnego_blob_len,
1699 						    0);
1700 		if (rc)
1701 			return -ENOMEM;
1702 
1703 		memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
1704 		rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1705 		kfree(spnego_blob);
1706 	}
1707 
1708 	user = session_user(conn, req);
1709 	if (!user) {
1710 		ksmbd_debug(SMB, "Unknown user name or an error\n");
1711 		return -EPERM;
1712 	}
1713 
1714 	if (sess->state == SMB2_SESSION_VALID) {
1715 		/*
1716 		 * Reuse session if anonymous try to connect
1717 		 * on reauthetication.
1718 		 */
1719 		if (conn->binding == false && ksmbd_anonymous_user(user)) {
1720 			ksmbd_free_user(user);
1721 			return 0;
1722 		}
1723 
1724 		if (!ksmbd_compare_user(sess->user, user)) {
1725 			ksmbd_free_user(user);
1726 			return -EKEYREJECTED;
1727 		}
1728 		ksmbd_free_user(user);
1729 	} else {
1730 		sess->user = user;
1731 	}
1732 
1733 	if (conn->binding == false && user_guest(sess->user)) {
1734 		rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1735 	} else {
1736 		struct authenticate_message *authblob;
1737 
1738 		authblob = user_authblob(conn, req);
1739 		if (conn->use_spnego && conn->mechToken)
1740 			sz = conn->mechTokenLen;
1741 		else
1742 			sz = le16_to_cpu(req->SecurityBufferLength);
1743 		rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess,
1744 						    auth_key);
1745 		if (rc) {
1746 			set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1747 			ksmbd_debug(SMB, "authentication failed\n");
1748 			rc = -EPERM;
1749 			goto out;
1750 		}
1751 	}
1752 
1753 	prev_id = le64_to_cpu(req->PreviousSessionId);
1754 	if (prev_id && prev_id != sess->id)
1755 		destroy_previous_session(conn, sess->user, prev_id);
1756 
1757 	/*
1758 	 * If session state is SMB2_SESSION_VALID, We can assume
1759 	 * that it is reauthentication. And the user/password
1760 	 * has been verified, so return it here.
1761 	 */
1762 	if (sess->state == SMB2_SESSION_VALID) {
1763 		if (conn->binding)
1764 			goto binding_session;
1765 		return 0;
1766 	}
1767 
1768 	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1769 	     (conn->sign || server_conf.enforced_signing)) ||
1770 	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1771 		sess->sign = true;
1772 
1773 	if (smb3_encryption_negotiated(conn) &&
1774 			!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1775 		conn->ops->generate_encryptionkey(conn, sess);
1776 		sess->enc = true;
1777 		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1778 			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1779 		/*
1780 		 * signing is disable if encryption is enable
1781 		 * on this session
1782 		 */
1783 		sess->sign = false;
1784 	}
1785 
1786 binding_session:
1787 	if (conn->dialect >= SMB30_PROT_ID) {
1788 		rc = register_session_channel(sess, conn, auth_key);
1789 		if (rc)
1790 			goto out;
1791 	}
1792 
1793 	if (conn->ops->generate_signingkey) {
1794 		rc = conn->ops->generate_signingkey(sess, conn);
1795 		if (rc) {
1796 			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1797 			rc = -EINVAL;
1798 			goto out;
1799 		}
1800 	}
1801 
1802 	if (!ksmbd_conn_lookup_dialect(conn)) {
1803 		pr_err("fail to verify the dialect\n");
1804 		rc = -ENOENT;
1805 		goto out;
1806 	}
1807 	rc = 0;
1808 out:
1809 	if (binding)
1810 		memzero_explicit(channel_key, sizeof(channel_key));
1811 	return rc;
1812 }
1813 
1814 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1815 static int krb5_authenticate(struct ksmbd_work *work,
1816 			     struct smb2_sess_setup_req *req,
1817 			     struct smb2_sess_setup_rsp *rsp)
1818 {
1819 	struct ksmbd_conn *conn = work->conn;
1820 	struct ksmbd_session *sess = work->sess;
1821 	char *in_blob, *out_blob;
1822 	char channel_key[CIFS_KEY_SIZE] = {};
1823 	char *auth_key = conn->binding ? channel_key : sess->sess_key;
1824 	u64 prev_sess_id;
1825 	bool binding = conn->binding;
1826 	int in_len, out_len;
1827 	int retval;
1828 
1829 	in_blob = (char *)&req->hdr.ProtocolId +
1830 		le16_to_cpu(req->SecurityBufferOffset);
1831 	in_len = le16_to_cpu(req->SecurityBufferLength);
1832 	out_blob = (char *)&rsp->hdr.ProtocolId +
1833 		le16_to_cpu(rsp->SecurityBufferOffset);
1834 	out_len = work->response_sz -
1835 		(le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1836 
1837 	retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1838 					 out_blob, &out_len, auth_key);
1839 	if (retval) {
1840 		ksmbd_debug(SMB, "krb5 authentication failed\n");
1841 		if (retval != -EKEYREJECTED)
1842 			retval = -EINVAL;
1843 		goto out;
1844 	}
1845 
1846 	/* Check previous session */
1847 	prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1848 	if (prev_sess_id && prev_sess_id != sess->id)
1849 		destroy_previous_session(conn, sess->user, prev_sess_id);
1850 
1851 	rsp->SecurityBufferLength = cpu_to_le16(out_len);
1852 
1853 	/*
1854 	 * If session state is SMB2_SESSION_VALID, We can assume
1855 	 * that it is reauthentication. And the user/password
1856 	 * has been verified, so return it here.
1857 	 */
1858 	if (sess->state == SMB2_SESSION_VALID) {
1859 		if (conn->binding)
1860 			goto binding_session;
1861 		return 0;
1862 	}
1863 
1864 	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1865 	    (conn->sign || server_conf.enforced_signing)) ||
1866 	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1867 		sess->sign = true;
1868 
1869 	if (smb3_encryption_negotiated(conn) &&
1870 	    !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1871 		conn->ops->generate_encryptionkey(conn, sess);
1872 		sess->enc = true;
1873 		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1874 			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1875 		sess->sign = false;
1876 	}
1877 
1878 binding_session:
1879 	if (conn->dialect >= SMB30_PROT_ID) {
1880 		retval = register_session_channel(sess, conn, auth_key);
1881 		if (retval)
1882 			goto out;
1883 	}
1884 
1885 	if (conn->ops->generate_signingkey) {
1886 		retval = conn->ops->generate_signingkey(sess, conn);
1887 		if (retval) {
1888 			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1889 			retval = -EINVAL;
1890 			goto out;
1891 		}
1892 	}
1893 
1894 	if (!ksmbd_conn_lookup_dialect(conn)) {
1895 		pr_err("fail to verify the dialect\n");
1896 		retval = -ENOENT;
1897 		goto out;
1898 	}
1899 	retval = 0;
1900 out:
1901 	if (binding)
1902 		memzero_explicit(channel_key, sizeof(channel_key));
1903 	return retval;
1904 }
1905 #else
1906 static int krb5_authenticate(struct ksmbd_work *work,
1907 			     struct smb2_sess_setup_req *req,
1908 			     struct smb2_sess_setup_rsp *rsp)
1909 {
1910 	return -EOPNOTSUPP;
1911 }
1912 #endif
1913 
1914 int smb2_sess_setup(struct ksmbd_work *work)
1915 {
1916 	struct ksmbd_conn *conn = work->conn;
1917 	struct smb2_sess_setup_req *req;
1918 	struct smb2_sess_setup_rsp *rsp;
1919 	struct ksmbd_session *sess;
1920 	struct negotiate_message *negblob;
1921 	unsigned int negblob_len, negblob_off;
1922 	int rc = 0;
1923 
1924 	ksmbd_debug(SMB, "Received smb2 session setup request\n");
1925 
1926 	if (!ksmbd_conn_need_setup(conn) && !ksmbd_conn_good(conn)) {
1927 		work->send_no_response = 1;
1928 		return rc;
1929 	}
1930 
1931 	WORK_BUFFERS(work, req, rsp);
1932 
1933 	rsp->StructureSize = cpu_to_le16(9);
1934 	rsp->SessionFlags = 0;
1935 	rsp->SecurityBufferOffset = cpu_to_le16(72);
1936 	rsp->SecurityBufferLength = 0;
1937 
1938 	ksmbd_conn_lock(conn);
1939 	if (!req->hdr.SessionId) {
1940 		sess = ksmbd_smb2_session_create();
1941 		if (!sess) {
1942 			rc = -ENOMEM;
1943 			goto out_err;
1944 		}
1945 		rsp->hdr.SessionId = cpu_to_le64(sess->id);
1946 		rc = ksmbd_session_register(conn, sess);
1947 		if (rc)
1948 			goto out_err;
1949 
1950 		conn->binding = false;
1951 	} else if (conn->dialect >= SMB30_PROT_ID &&
1952 		   (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1953 		   req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1954 		u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1955 
1956 		sess = ksmbd_session_lookup_slowpath(sess_id);
1957 		if (!sess) {
1958 			rc = -ENOENT;
1959 			goto out_err;
1960 		}
1961 
1962 		if (conn->dialect != sess->dialect) {
1963 			rc = -EINVAL;
1964 			goto out_err;
1965 		}
1966 
1967 		if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1968 			rc = -EINVAL;
1969 			goto out_err;
1970 		}
1971 
1972 		if (memcmp(conn->ClientGUID, sess->ClientGUID,
1973 			    SMB2_CLIENT_GUID_SIZE)) {
1974 			rc = -ENOENT;
1975 			goto out_err;
1976 		}
1977 
1978 		if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1979 			rc = -EACCES;
1980 			goto out_err;
1981 		}
1982 
1983 		if (sess->state == SMB2_SESSION_EXPIRED) {
1984 			rc = -EFAULT;
1985 			goto out_err;
1986 		}
1987 
1988 		if (ksmbd_conn_need_reconnect(conn)) {
1989 			rc = -EFAULT;
1990 			ksmbd_user_session_put(sess);
1991 			sess = NULL;
1992 			goto out_err;
1993 		}
1994 
1995 		if (is_ksmbd_session_in_connection(conn, sess_id)) {
1996 			rc = -EACCES;
1997 			goto out_err;
1998 		}
1999 
2000 		if (user_guest(sess->user)) {
2001 			rc = -EOPNOTSUPP;
2002 			goto out_err;
2003 		}
2004 
2005 		conn->binding = true;
2006 	} else if ((conn->dialect < SMB30_PROT_ID ||
2007 		    server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
2008 		   (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2009 		sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId));
2010 		if (sess) {
2011 			int sign_ret;
2012 
2013 			work->sess = sess;
2014 			if (sess->dialect >= SMB30_PROT_ID)
2015 				sign_ret = smb3_check_sign_req(work);
2016 			else
2017 				sign_ret = smb2_check_sign_req(work);
2018 			if (sess->state != SMB2_SESSION_VALID ||
2019 			    !(req->hdr.Flags & SMB2_FLAGS_SIGNED) ||
2020 			    !sign_ret) {
2021 				ksmbd_user_session_put(sess);
2022 				work->sess = NULL;
2023 				sess = NULL;
2024 			}
2025 		}
2026 		rc = -EACCES;
2027 		goto out_err;
2028 	} else {
2029 		sess = ksmbd_session_lookup(conn,
2030 					    le64_to_cpu(req->hdr.SessionId));
2031 		if (!sess) {
2032 			sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId));
2033 			if (sess && !lookup_chann_list(sess, conn)) {
2034 				ksmbd_user_session_put(sess);
2035 				sess = NULL;
2036 			}
2037 		}
2038 		if (!sess) {
2039 			rc = -ENOENT;
2040 			goto out_err;
2041 		}
2042 
2043 		if (sess->state == SMB2_SESSION_EXPIRED) {
2044 			rc = -EFAULT;
2045 			goto out_err;
2046 		}
2047 
2048 		if (ksmbd_conn_need_reconnect(conn)) {
2049 			rc = -EFAULT;
2050 			ksmbd_user_session_put(sess);
2051 			sess = NULL;
2052 			goto out_err;
2053 		}
2054 
2055 		conn->binding = false;
2056 	}
2057 	work->sess = sess;
2058 
2059 	negblob_off = le16_to_cpu(req->SecurityBufferOffset);
2060 	negblob_len = le16_to_cpu(req->SecurityBufferLength);
2061 	if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) {
2062 		rc = -EINVAL;
2063 		goto out_err;
2064 	}
2065 
2066 	negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
2067 			negblob_off);
2068 
2069 	if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
2070 		if (conn->mechToken) {
2071 			negblob = (struct negotiate_message *)conn->mechToken;
2072 			negblob_len = conn->mechTokenLen;
2073 		}
2074 	}
2075 
2076 	if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
2077 		rc = -EINVAL;
2078 		goto out_err;
2079 	}
2080 
2081 	if (server_conf.auth_mechs & conn->auth_mechs) {
2082 		rc = generate_preauth_hash(work);
2083 		if (rc)
2084 			goto out_err;
2085 
2086 		if (conn->preferred_auth_mech &
2087 				(KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
2088 			rc = krb5_authenticate(work, req, rsp);
2089 			if (rc) {
2090 				rc = -EINVAL;
2091 				goto out_err;
2092 			}
2093 
2094 			if (!ksmbd_conn_need_reconnect(conn)) {
2095 				ksmbd_conn_set_good(conn);
2096 				sess->state = SMB2_SESSION_VALID;
2097 			}
2098 		} else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
2099 			if (negblob->MessageType == NtLmNegotiate) {
2100 				rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
2101 				if (rc)
2102 					goto out_err;
2103 				rsp->hdr.Status =
2104 					STATUS_MORE_PROCESSING_REQUIRED;
2105 			} else if (negblob->MessageType == NtLmAuthenticate) {
2106 				rc = ntlm_authenticate(work, req, rsp);
2107 				if (rc)
2108 					goto out_err;
2109 
2110 				if (!ksmbd_conn_need_reconnect(conn)) {
2111 					ksmbd_conn_set_good(conn);
2112 					sess->state = SMB2_SESSION_VALID;
2113 				}
2114 				if (conn->binding) {
2115 					struct preauth_session *preauth_sess;
2116 
2117 					preauth_sess =
2118 						ksmbd_preauth_session_lookup(conn, sess->id);
2119 					if (preauth_sess) {
2120 						list_del(&preauth_sess->preauth_entry);
2121 						kfree(preauth_sess);
2122 					}
2123 				}
2124 			} else {
2125 				pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
2126 						le32_to_cpu(negblob->MessageType));
2127 				rc = -EINVAL;
2128 			}
2129 		} else {
2130 			/* TODO: need one more negotiation */
2131 			pr_err("Not support the preferred authentication\n");
2132 			rc = -EINVAL;
2133 		}
2134 	} else {
2135 		pr_err("Not support authentication\n");
2136 		rc = -EINVAL;
2137 	}
2138 
2139 out_err:
2140 	if (rc == -EINVAL)
2141 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2142 	else if (rc == -ENOENT)
2143 		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
2144 	else if (rc == -EACCES)
2145 		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
2146 	else if (rc == -EFAULT)
2147 		rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
2148 	else if (rc == -ENOMEM || rc == -ENOSPC)
2149 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2150 	else if (rc == -EOPNOTSUPP)
2151 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
2152 	else if (rc == -EKEYREJECTED)
2153 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2154 	else if (rc)
2155 		rsp->hdr.Status = STATUS_LOGON_FAILURE;
2156 	if ((rsp->hdr.Status == STATUS_USER_SESSION_DELETED ||
2157 	     (rsp->hdr.Status == STATUS_INVALID_PARAMETER &&
2158 	      (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING))) &&
2159 	    (req->hdr.Flags & SMB2_FLAGS_SIGNED))
2160 		rsp->hdr.Flags |= SMB2_FLAGS_SIGNED;
2161 
2162 	if (conn->mechToken) {
2163 		kfree(conn->mechToken);
2164 		conn->mechToken = NULL;
2165 	}
2166 
2167 	if (rc < 0) {
2168 		if (sess && conn->dialect == SMB311_PROT_ID &&
2169 		    (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2170 			struct preauth_session *preauth_sess;
2171 
2172 			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
2173 			if (preauth_sess) {
2174 				list_del(&preauth_sess->preauth_entry);
2175 				kfree(preauth_sess);
2176 			}
2177 		}
2178 
2179 		/*
2180 		 * SecurityBufferOffset should be set to zero
2181 		 * in session setup error response.
2182 		 */
2183 		rsp->SecurityBufferOffset = 0;
2184 
2185 		if (sess) {
2186 			bool try_delay = false;
2187 
2188 			/*
2189 			 * To avoid dictionary attacks (repeated session setups rapidly sent) to
2190 			 * connect to server, ksmbd make a delay of a 5 seconds on session setup
2191 			 * failure to make it harder to send enough random connection requests
2192 			 * to break into a server.
2193 			 */
2194 			if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
2195 				try_delay = true;
2196 
2197 			/*
2198 			 * For binding requests, session belongs to another
2199 			 * connection. Do not expire it.
2200 			 */
2201 			if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2202 				sess->last_active = jiffies;
2203 				sess->state = SMB2_SESSION_EXPIRED;
2204 			}
2205 			/*
2206 			 * Keep the binding session reference until the response is
2207 			 * signed and sent.  Error responses for a signed binding
2208 			 * request are signed with the existing session signing key.
2209 			 */
2210 			if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) ||
2211 			    work->sess != sess) {
2212 				ksmbd_user_session_put(sess);
2213 				work->sess = NULL;
2214 			}
2215 			if (try_delay) {
2216 				ksmbd_conn_set_need_reconnect(conn);
2217 				ssleep(5);
2218 				ksmbd_conn_set_need_setup(conn);
2219 			}
2220 		}
2221 		smb2_set_err_rsp(work);
2222 		conn->binding = false;
2223 	} else {
2224 		unsigned int iov_len;
2225 
2226 		if (rsp->SecurityBufferLength)
2227 			iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
2228 				le16_to_cpu(rsp->SecurityBufferLength);
2229 		else
2230 			iov_len = sizeof(struct smb2_sess_setup_rsp);
2231 		rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
2232 		if (rc)
2233 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2234 	}
2235 
2236 	ksmbd_conn_unlock(conn);
2237 	return rc;
2238 }
2239 
2240 /**
2241  * smb2_tree_connect() - handler for smb2 tree connect command
2242  * @work:	smb work containing smb request buffer
2243  *
2244  * Return:      0 on success, otherwise error
2245  */
2246 int smb2_tree_connect(struct ksmbd_work *work)
2247 {
2248 	struct ksmbd_conn *conn = work->conn;
2249 	struct smb2_tree_connect_req *req;
2250 	struct smb2_tree_connect_rsp *rsp;
2251 	struct ksmbd_session *sess = work->sess;
2252 	char *treename = NULL, *name = NULL;
2253 	struct ksmbd_tree_conn_status status;
2254 	struct ksmbd_share_config *share = NULL;
2255 	int rc = -EINVAL;
2256 
2257 	ksmbd_debug(SMB, "Received smb2 tree connect request\n");
2258 
2259 	WORK_BUFFERS(work, req, rsp);
2260 
2261 	treename = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->PathOffset),
2262 					  le16_to_cpu(req->PathLength), true,
2263 					  conn->local_nls);
2264 	if (IS_ERR(treename)) {
2265 		pr_err("treename is NULL\n");
2266 		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2267 		goto out_err1;
2268 	}
2269 
2270 	name = ksmbd_extract_sharename(conn->um, treename);
2271 	if (IS_ERR(name)) {
2272 		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2273 		goto out_err1;
2274 	}
2275 
2276 	ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
2277 		    name, treename);
2278 
2279 	status = ksmbd_tree_conn_connect(work, name);
2280 	if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
2281 		rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
2282 	else
2283 		goto out_err1;
2284 
2285 	share = status.tree_conn->share_conf;
2286 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2287 		ksmbd_debug(SMB, "IPC share path request\n");
2288 		rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
2289 		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2290 			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
2291 			FILE_DELETE_LE | FILE_READ_CONTROL_LE |
2292 			FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2293 			FILE_SYNCHRONIZE_LE;
2294 	} else {
2295 		rsp->ShareType = SMB2_SHARE_TYPE_DISK;
2296 		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2297 			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
2298 		if (test_tree_conn_flag(status.tree_conn,
2299 					KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2300 			rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
2301 				FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
2302 				FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
2303 				FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
2304 				FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2305 				FILE_SYNCHRONIZE_LE;
2306 		}
2307 	}
2308 
2309 	status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2310 	if (conn->posix_ext_supported)
2311 		status.tree_conn->posix_extensions = true;
2312 
2313 	down_write(&sess->tree_conns_lock);
2314 	status.tree_conn->t_state = TREE_CONNECTED;
2315 	up_write(&sess->tree_conns_lock);
2316 	rsp->StructureSize = cpu_to_le16(16);
2317 out_err1:
2318 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE && share &&
2319 	    test_share_config_flag(share,
2320 				   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
2321 		rsp->Capabilities = SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY;
2322 	else
2323 		rsp->Capabilities = 0;
2324 	rsp->Reserved = 0;
2325 	/* default manual caching */
2326 	rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2327 	/* Tell the client that READ requests may request compressed responses. */
2328 	if (conn->dialect == SMB311_PROT_ID &&
2329 	    conn->compress_algorithm != SMB3_COMPRESS_NONE)
2330 		rsp->ShareFlags |= cpu_to_le32(SMB2_SHAREFLAG_COMPRESS_DATA);
2331 
2332 	rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2333 	if (rc)
2334 		status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2335 
2336 	if (!IS_ERR(treename))
2337 		kfree(treename);
2338 	if (!IS_ERR(name))
2339 		kfree(name);
2340 
2341 	switch (status.ret) {
2342 	case KSMBD_TREE_CONN_STATUS_OK:
2343 		rsp->hdr.Status = STATUS_SUCCESS;
2344 		rc = 0;
2345 		break;
2346 	case -ESTALE:
2347 	case -ENOENT:
2348 	case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2349 		rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2350 		break;
2351 	case -ENOMEM:
2352 	case KSMBD_TREE_CONN_STATUS_NOMEM:
2353 		rsp->hdr.Status = STATUS_NO_MEMORY;
2354 		break;
2355 	case KSMBD_TREE_CONN_STATUS_ERROR:
2356 	case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2357 	case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2358 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2359 		break;
2360 	case -EINVAL:
2361 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2362 		break;
2363 	default:
2364 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2365 	}
2366 
2367 	if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2368 		smb2_set_err_rsp(work);
2369 
2370 	return rc;
2371 }
2372 
2373 /**
2374  * smb2_create_open_flags() - convert smb open flags to unix open flags
2375  * @file_present:	is file already present
2376  * @access:		file access flags
2377  * @disposition:	file disposition flags
2378  * @may_flags:		set with MAY_ flags
2379  * @coptions:		file creation options
2380  * @mode:		file mode
2381  *
2382  * Return:      file open flags
2383  */
2384 static int smb2_create_open_flags(bool file_present, __le32 access,
2385 				  __le32 disposition,
2386 				  int *may_flags,
2387 				  __le32 coptions,
2388 				  umode_t mode)
2389 {
2390 	int oflags = O_NONBLOCK | O_LARGEFILE;
2391 
2392 	if (coptions & FILE_DIRECTORY_FILE_LE || S_ISDIR(mode)) {
2393 		access &= ~FILE_WRITE_DESIRE_ACCESS_LE;
2394 		ksmbd_debug(SMB, "Discard write access to a directory\n");
2395 	}
2396 
2397 	if (access & FILE_READ_DESIRED_ACCESS_LE &&
2398 	    access & FILE_WRITE_DESIRE_ACCESS_LE) {
2399 		oflags |= O_RDWR;
2400 		*may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2401 	} else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2402 		oflags |= O_WRONLY;
2403 		*may_flags = MAY_OPEN | MAY_WRITE;
2404 	} else {
2405 		oflags |= O_RDONLY;
2406 		*may_flags = MAY_OPEN | MAY_READ;
2407 	}
2408 
2409 	if (access == FILE_READ_ATTRIBUTES_LE || S_ISBLK(mode) || S_ISCHR(mode))
2410 		oflags |= O_PATH;
2411 
2412 	if (file_present) {
2413 		switch (disposition & FILE_CREATE_MASK_LE) {
2414 		case FILE_OPEN_LE:
2415 		case FILE_CREATE_LE:
2416 			break;
2417 		case FILE_SUPERSEDE_LE:
2418 		case FILE_OVERWRITE_LE:
2419 		case FILE_OVERWRITE_IF_LE:
2420 			oflags |= O_TRUNC;
2421 			break;
2422 		default:
2423 			break;
2424 		}
2425 	} else {
2426 		switch (disposition & FILE_CREATE_MASK_LE) {
2427 		case FILE_SUPERSEDE_LE:
2428 		case FILE_CREATE_LE:
2429 		case FILE_OPEN_IF_LE:
2430 		case FILE_OVERWRITE_IF_LE:
2431 			oflags |= O_CREAT;
2432 			break;
2433 		case FILE_OPEN_LE:
2434 		case FILE_OVERWRITE_LE:
2435 			oflags &= ~O_CREAT;
2436 			break;
2437 		default:
2438 			break;
2439 		}
2440 	}
2441 
2442 	return oflags;
2443 }
2444 
2445 /**
2446  * smb2_tree_disconnect() - handler for smb tree connect request
2447  * @work:	smb work containing request buffer
2448  *
2449  * Return:      0 on success, otherwise error
2450  */
2451 int smb2_tree_disconnect(struct ksmbd_work *work)
2452 {
2453 	struct smb2_tree_disconnect_rsp *rsp;
2454 	struct smb2_tree_disconnect_req *req;
2455 	struct ksmbd_session *sess = work->sess;
2456 	struct ksmbd_tree_connect *tcon = work->tcon;
2457 	int err;
2458 
2459 	ksmbd_debug(SMB, "Received smb2 tree disconnect request\n");
2460 
2461 	WORK_BUFFERS(work, req, rsp);
2462 
2463 	if (!tcon) {
2464 		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2465 
2466 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2467 		err = -ENOENT;
2468 		goto err_out;
2469 	}
2470 
2471 	ksmbd_close_tree_conn_fds(work);
2472 
2473 	down_write(&sess->tree_conns_lock);
2474 	if (tcon->t_state == TREE_DISCONNECTED) {
2475 		up_write(&sess->tree_conns_lock);
2476 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2477 		err = -ENOENT;
2478 		goto err_out;
2479 	}
2480 
2481 	tcon->t_state = TREE_DISCONNECTED;
2482 	up_write(&sess->tree_conns_lock);
2483 
2484 	err = ksmbd_tree_conn_disconnect(sess, tcon);
2485 	if (err) {
2486 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2487 		goto err_out;
2488 	}
2489 
2490 	rsp->StructureSize = cpu_to_le16(4);
2491 	err = ksmbd_iov_pin_rsp(work, rsp,
2492 				sizeof(struct smb2_tree_disconnect_rsp));
2493 	if (err) {
2494 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2495 		goto err_out;
2496 	}
2497 
2498 	return 0;
2499 
2500 err_out:
2501 	smb2_set_err_rsp(work);
2502 	return err;
2503 
2504 }
2505 
2506 /**
2507  * smb2_session_logoff() - handler for session log off request
2508  * @work:	smb work containing request buffer
2509  *
2510  * Return:      0 on success, otherwise error
2511  */
2512 int smb2_session_logoff(struct ksmbd_work *work)
2513 {
2514 	struct ksmbd_conn *conn = work->conn;
2515 	struct ksmbd_session *sess = work->sess;
2516 	struct smb2_logoff_req *req;
2517 	struct smb2_logoff_rsp *rsp;
2518 	u64 sess_id;
2519 	int err;
2520 
2521 	WORK_BUFFERS(work, req, rsp);
2522 
2523 	ksmbd_debug(SMB, "Received smb2 session logoff request\n");
2524 
2525 	ksmbd_conn_lock(conn);
2526 	if (!ksmbd_conn_good(conn)) {
2527 		ksmbd_conn_unlock(conn);
2528 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2529 		smb2_set_err_rsp(work);
2530 		return -ENOENT;
2531 	}
2532 	sess_id = le64_to_cpu(req->hdr.SessionId);
2533 	ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2534 	ksmbd_conn_unlock(conn);
2535 
2536 	ksmbd_close_session_fds(work);
2537 	ksmbd_conn_wait_idle(conn);
2538 
2539 	if (ksmbd_tree_conn_session_logoff(sess)) {
2540 		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2541 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2542 		smb2_set_err_rsp(work);
2543 		return -ENOENT;
2544 	}
2545 
2546 	down_write(&conn->session_lock);
2547 	sess->state = SMB2_SESSION_EXPIRED;
2548 	up_write(&conn->session_lock);
2549 
2550 	ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_SETUP);
2551 
2552 	rsp->StructureSize = cpu_to_le16(4);
2553 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
2554 	if (err) {
2555 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2556 		smb2_set_err_rsp(work);
2557 		return err;
2558 	}
2559 	return 0;
2560 }
2561 
2562 /**
2563  * create_smb2_pipe() - create IPC pipe
2564  * @work:	smb work containing request buffer
2565  *
2566  * Return:      0 on success, otherwise error
2567  */
2568 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2569 {
2570 	struct smb2_create_rsp *rsp;
2571 	struct smb2_create_req *req;
2572 	int id = -1;
2573 	int err;
2574 	char *name;
2575 
2576 	WORK_BUFFERS(work, req, rsp);
2577 
2578 	name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2579 				      1, work->conn->local_nls);
2580 	if (IS_ERR(name)) {
2581 		rsp->hdr.Status = STATUS_NO_MEMORY;
2582 		err = PTR_ERR(name);
2583 		goto out;
2584 	}
2585 
2586 	id = ksmbd_session_rpc_open(work->sess, name);
2587 	if (id < 0) {
2588 		pr_err("Unable to open RPC pipe: %d\n", id);
2589 		err = id;
2590 		goto out;
2591 	}
2592 
2593 	rsp->hdr.Status = STATUS_SUCCESS;
2594 	rsp->StructureSize = cpu_to_le16(89);
2595 	rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2596 	rsp->Flags = 0;
2597 	rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2598 
2599 	rsp->CreationTime = cpu_to_le64(0);
2600 	rsp->LastAccessTime = cpu_to_le64(0);
2601 	rsp->ChangeTime = cpu_to_le64(0);
2602 	rsp->AllocationSize = cpu_to_le64(0);
2603 	rsp->EndofFile = cpu_to_le64(0);
2604 	rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2605 	rsp->Reserved2 = 0;
2606 	rsp->VolatileFileId = id;
2607 	rsp->PersistentFileId = 0;
2608 	rsp->CreateContextsOffset = 0;
2609 	rsp->CreateContextsLength = 0;
2610 
2611 	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
2612 	if (err)
2613 		goto out;
2614 
2615 	kfree(name);
2616 	return 0;
2617 
2618 out:
2619 	switch (err) {
2620 	case -EINVAL:
2621 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2622 		break;
2623 	case -ENOSPC:
2624 	case -ENOMEM:
2625 		rsp->hdr.Status = STATUS_NO_MEMORY;
2626 		break;
2627 	}
2628 
2629 	if (id >= 0)
2630 		ksmbd_session_rpc_close(work->sess, id);
2631 
2632 	if (!IS_ERR(name))
2633 		kfree(name);
2634 
2635 	smb2_set_err_rsp(work);
2636 	return err;
2637 }
2638 
2639 /**
2640  * smb2_set_ea() - handler for setting extended attributes using set
2641  *		info command
2642  * @eabuf:	set info command buffer
2643  * @buf_len:	set info command buffer length
2644  * @path:	dentry path for get ea
2645  * @get_write:	get write access to a mount
2646  *
2647  * Return:	0 on success, otherwise error
2648  */
2649 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2650 		       const struct path *path, bool get_write)
2651 {
2652 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2653 	char *attr_name = NULL, *value;
2654 	int rc = 0;
2655 	unsigned int next = 0;
2656 
2657 	if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
2658 			le16_to_cpu(eabuf->EaValueLength))
2659 		return -EINVAL;
2660 
2661 	attr_name = kmalloc(XATTR_NAME_MAX + 1, KSMBD_DEFAULT_GFP);
2662 	if (!attr_name)
2663 		return -ENOMEM;
2664 
2665 	do {
2666 		if (!eabuf->EaNameLength)
2667 			goto next;
2668 
2669 		ksmbd_debug(SMB,
2670 			    "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2671 			    eabuf->name, eabuf->EaNameLength,
2672 			    le16_to_cpu(eabuf->EaValueLength),
2673 			    le32_to_cpu(eabuf->NextEntryOffset));
2674 
2675 		if (eabuf->EaNameLength >
2676 		    (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2677 			rc = -EINVAL;
2678 			break;
2679 		}
2680 
2681 		memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2682 		memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2683 		       eabuf->EaNameLength);
2684 		attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2685 		value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2686 
2687 		if (!eabuf->EaValueLength) {
2688 			rc = ksmbd_vfs_casexattr_len(idmap,
2689 						     path->dentry,
2690 						     attr_name,
2691 						     XATTR_USER_PREFIX_LEN +
2692 						     eabuf->EaNameLength);
2693 
2694 			/* delete the EA only when it exits */
2695 			if (rc > 0) {
2696 				rc = ksmbd_vfs_remove_xattr(idmap,
2697 							    path,
2698 							    attr_name,
2699 							    get_write);
2700 
2701 				if (rc < 0) {
2702 					ksmbd_debug(SMB,
2703 						    "remove xattr failed(%d)\n",
2704 						    rc);
2705 					break;
2706 				}
2707 			}
2708 
2709 			/* if the EA doesn't exist, just do nothing. */
2710 			rc = 0;
2711 		} else {
2712 			rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
2713 						le16_to_cpu(eabuf->EaValueLength),
2714 						0, get_write);
2715 			if (rc < 0) {
2716 				ksmbd_debug(SMB,
2717 					    "ksmbd_vfs_setxattr is failed(%d)\n",
2718 					    rc);
2719 				break;
2720 			}
2721 		}
2722 
2723 next:
2724 		next = le32_to_cpu(eabuf->NextEntryOffset);
2725 		if (next == 0 || buf_len < next)
2726 			break;
2727 		buf_len -= next;
2728 		eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2729 		if (buf_len < sizeof(struct smb2_ea_info)) {
2730 			rc = -EINVAL;
2731 			break;
2732 		}
2733 
2734 		if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
2735 				le16_to_cpu(eabuf->EaValueLength)) {
2736 			rc = -EINVAL;
2737 			break;
2738 		}
2739 	} while (next != 0);
2740 
2741 	kfree(attr_name);
2742 	return rc;
2743 }
2744 
2745 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2746 					       struct ksmbd_file *fp,
2747 					       char *stream_name, int s_type)
2748 {
2749 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2750 	size_t xattr_stream_size;
2751 	char *xattr_stream_name;
2752 	int rc;
2753 
2754 	rc = ksmbd_vfs_xattr_stream_name(stream_name,
2755 					 &xattr_stream_name,
2756 					 &xattr_stream_size,
2757 					 s_type);
2758 	if (rc)
2759 		return rc;
2760 
2761 	fp->stream.name = xattr_stream_name;
2762 	fp->stream.size = xattr_stream_size;
2763 
2764 	/* Check if there is stream prefix in xattr space */
2765 	rc = ksmbd_vfs_casexattr_len(idmap,
2766 				     path->dentry,
2767 				     xattr_stream_name,
2768 				     xattr_stream_size);
2769 	if (rc >= 0)
2770 		return 0;
2771 
2772 	if (fp->cdoption == FILE_OPEN_LE) {
2773 		ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2774 		return -EBADF;
2775 	}
2776 
2777 	rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false);
2778 	if (rc < 0)
2779 		pr_err("Failed to store XATTR stream name :%d\n", rc);
2780 	return 0;
2781 }
2782 
2783 static int smb2_remove_smb_xattrs(const struct path *path)
2784 {
2785 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2786 	char *name, *xattr_list = NULL;
2787 	ssize_t xattr_list_len;
2788 	int err = 0;
2789 
2790 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2791 	if (xattr_list_len < 0) {
2792 		goto out;
2793 	} else if (!xattr_list_len) {
2794 		ksmbd_debug(SMB, "empty xattr in the file\n");
2795 		goto out;
2796 	}
2797 
2798 	for (name = xattr_list; name - xattr_list < xattr_list_len;
2799 			name += strlen(name) + 1) {
2800 		ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2801 
2802 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2803 		    !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2804 			     STREAM_PREFIX_LEN)) {
2805 			err = ksmbd_vfs_remove_xattr(idmap, path,
2806 						     name, true);
2807 			if (err)
2808 				ksmbd_debug(SMB, "remove xattr failed : %s\n",
2809 					    name);
2810 		}
2811 	}
2812 out:
2813 	kvfree(xattr_list);
2814 	return err;
2815 }
2816 
2817 static int smb2_create_truncate(const struct path *path)
2818 {
2819 	int rc = vfs_truncate(path, 0);
2820 
2821 	if (rc) {
2822 		pr_err("vfs_truncate failed, rc %d\n", rc);
2823 		return rc;
2824 	}
2825 
2826 	rc = smb2_remove_smb_xattrs(path);
2827 	if (rc == -EOPNOTSUPP)
2828 		rc = 0;
2829 	if (rc)
2830 		ksmbd_debug(SMB,
2831 			    "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2832 			    rc);
2833 	return rc;
2834 }
2835 
2836 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2837 			    struct ksmbd_file *fp)
2838 {
2839 	struct xattr_dos_attrib da = {0};
2840 	int rc;
2841 
2842 	if (!test_share_config_flag(tcon->share_conf,
2843 				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2844 		return;
2845 
2846 	da.version = 4;
2847 	da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2848 	da.itime = da.create_time = fp->create_time;
2849 	da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2850 		XATTR_DOSINFO_ITIME;
2851 
2852 	rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, true);
2853 	if (rc)
2854 		ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2855 }
2856 
2857 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2858 			       const struct path *path, struct ksmbd_file *fp)
2859 {
2860 	struct xattr_dos_attrib da;
2861 	int rc;
2862 
2863 	fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2864 
2865 	/* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2866 	if (!test_share_config_flag(tcon->share_conf,
2867 				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2868 		return;
2869 
2870 	rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2871 					    path->dentry, &da);
2872 	if (rc > 0) {
2873 		fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2874 		fp->create_time = da.create_time;
2875 		fp->itime = da.itime;
2876 	}
2877 }
2878 
2879 static int smb2_creat(struct ksmbd_work *work,
2880 		      struct path *path, char *name, int open_flags,
2881 		      umode_t posix_mode, bool is_dir)
2882 {
2883 	struct ksmbd_tree_connect *tcon = work->tcon;
2884 	struct ksmbd_share_config *share = tcon->share_conf;
2885 	umode_t mode;
2886 	int rc;
2887 
2888 	if (!(open_flags & O_CREAT))
2889 		return -EBADF;
2890 
2891 	ksmbd_debug(SMB, "file does not exist, so creating\n");
2892 	if (is_dir == true) {
2893 		ksmbd_debug(SMB, "creating directory\n");
2894 
2895 		mode = share_config_directory_mode(share, posix_mode);
2896 		rc = ksmbd_vfs_mkdir(work, name, mode);
2897 		if (rc)
2898 			return rc;
2899 	} else {
2900 		ksmbd_debug(SMB, "creating regular file\n");
2901 
2902 		mode = share_config_create_mode(share, posix_mode);
2903 		rc = ksmbd_vfs_create(work, name, mode);
2904 		if (rc)
2905 			return rc;
2906 	}
2907 
2908 	rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2909 	if (rc) {
2910 		pr_err("cannot get linux path (%s), err = %d\n",
2911 		       name, rc);
2912 		return rc;
2913 	}
2914 	return 0;
2915 }
2916 
2917 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2918 				 struct smb2_create_req *req,
2919 				 const struct path *path)
2920 {
2921 	struct create_context *context;
2922 	struct create_sd_buf_req *sd_buf;
2923 
2924 	if (!req->CreateContextsOffset)
2925 		return -ENOENT;
2926 
2927 	/* Parse SD BUFFER create contexts */
2928 	context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2929 	if (!context)
2930 		return -ENOENT;
2931 	else if (IS_ERR(context))
2932 		return PTR_ERR(context);
2933 
2934 	ksmbd_debug(SMB,
2935 		    "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2936 	sd_buf = (struct create_sd_buf_req *)context;
2937 	if (le16_to_cpu(context->DataOffset) +
2938 	    le32_to_cpu(context->DataLength) <
2939 	    sizeof(struct create_sd_buf_req))
2940 		return -EINVAL;
2941 	return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2942 			    le32_to_cpu(sd_buf->ccontext.DataLength), true, false);
2943 }
2944 
2945 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2946 			     struct mnt_idmap *idmap,
2947 			     struct inode *inode)
2948 {
2949 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2950 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2951 
2952 	fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2953 	fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2954 	fattr->cf_mode = inode->i_mode;
2955 	fattr->cf_acls = NULL;
2956 	fattr->cf_dacls = NULL;
2957 
2958 	if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2959 		fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2960 		if (S_ISDIR(inode->i_mode))
2961 			fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2962 	}
2963 }
2964 
2965 enum {
2966 	DURABLE_RECONN_V2 = 1,
2967 	DURABLE_RECONN,
2968 	DURABLE_REQ_V2,
2969 	DURABLE_REQ,
2970 };
2971 
2972 struct durable_info {
2973 	struct ksmbd_file *fp;
2974 	unsigned short int type;
2975 	bool persistent;
2976 	bool reconnected;
2977 	bool app_instance_id;
2978 	unsigned int timeout;
2979 	char *CreateGuid;
2980 	char AppInstanceId[SMB2_CREATE_GUID_SIZE];
2981 };
2982 
2983 static int parse_durable_handle_context(struct ksmbd_work *work,
2984 					struct smb2_create_req *req,
2985 					struct lease_ctx_info *lc,
2986 					struct durable_info *dh_info)
2987 {
2988 	struct ksmbd_conn *conn = work->conn;
2989 	struct create_context *context;
2990 	int dh_idx, err = 0;
2991 	u64 persistent_id = 0;
2992 	int req_op_level;
2993 	static const char * const durable_arr[] = {"DH2C", "DHnC", "DH2Q", "DHnQ"};
2994 
2995 	req_op_level = req->RequestedOplockLevel;
2996 	for (dh_idx = DURABLE_RECONN_V2; dh_idx <= ARRAY_SIZE(durable_arr);
2997 	     dh_idx++) {
2998 		context = smb2_find_context_vals(req, durable_arr[dh_idx - 1], 4);
2999 		if (IS_ERR(context)) {
3000 			err = PTR_ERR(context);
3001 			goto out;
3002 		}
3003 		if (!context)
3004 			continue;
3005 
3006 		switch (dh_idx) {
3007 		case DURABLE_RECONN_V2:
3008 		{
3009 			struct create_durable_handle_reconnect_v2 *recon_v2;
3010 
3011 			if (dh_info->type == DURABLE_RECONN ||
3012 			    dh_info->type == DURABLE_REQ_V2) {
3013 				err = -EINVAL;
3014 				goto out;
3015 			}
3016 
3017 			if (le32_to_cpu(context->DataLength) <
3018 			    sizeof(recon_v2->dcontext)) {
3019 				err = -EINVAL;
3020 				goto out;
3021 			}
3022 
3023 			recon_v2 = (struct create_durable_handle_reconnect_v2 *)context;
3024 			persistent_id = recon_v2->dcontext.Fid.PersistentFileId;
3025 			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
3026 			if (!dh_info->fp) {
3027 				ksmbd_debug(SMB, "Failed to get durable handle state\n");
3028 				err = -EBADF;
3029 				goto out;
3030 			}
3031 
3032 			if (dh_info->fp->durable_volatile_id !=
3033 			    recon_v2->dcontext.Fid.VolatileFileId) {
3034 				err = -EBADF;
3035 				ksmbd_put_durable_fd(dh_info->fp);
3036 				goto out;
3037 			}
3038 
3039 			if (memcmp(dh_info->fp->create_guid, recon_v2->dcontext.CreateGuid,
3040 				   SMB2_CREATE_GUID_SIZE)) {
3041 				err = -EBADF;
3042 				ksmbd_put_durable_fd(dh_info->fp);
3043 				goto out;
3044 			}
3045 
3046 			dh_info->type = dh_idx;
3047 			dh_info->reconnected = true;
3048 			ksmbd_debug(SMB,
3049 				"reconnect v2 Persistent-id from reconnect = %llu\n",
3050 					persistent_id);
3051 			break;
3052 		}
3053 		case DURABLE_RECONN:
3054 		{
3055 			create_durable_reconn_t *recon;
3056 
3057 			if (dh_info->type == DURABLE_RECONN_V2 ||
3058 			    dh_info->type == DURABLE_REQ_V2) {
3059 				err = -EINVAL;
3060 				goto out;
3061 			}
3062 
3063 			if (le32_to_cpu(context->DataLength) <
3064 			    sizeof(recon->Data)) {
3065 				err = -EINVAL;
3066 				goto out;
3067 			}
3068 
3069 			recon = (create_durable_reconn_t *)context;
3070 			persistent_id = recon->Data.Fid.PersistentFileId;
3071 			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
3072 			if (!dh_info->fp) {
3073 				ksmbd_debug(SMB, "Failed to get durable handle state\n");
3074 				err = -EBADF;
3075 				goto out;
3076 			}
3077 
3078 			if (dh_info->fp->durable_volatile_id !=
3079 			    recon->Data.Fid.VolatileFileId) {
3080 				err = -EBADF;
3081 				ksmbd_put_durable_fd(dh_info->fp);
3082 				goto out;
3083 			}
3084 
3085 			dh_info->type = dh_idx;
3086 			dh_info->reconnected = true;
3087 			ksmbd_debug(SMB, "reconnect Persistent-id from reconnect = %llu\n",
3088 				    persistent_id);
3089 			break;
3090 		}
3091 		case DURABLE_REQ_V2:
3092 		{
3093 			struct create_durable_req_v2 *durable_v2_blob;
3094 
3095 			if (dh_info->type == DURABLE_RECONN ||
3096 			    dh_info->type == DURABLE_RECONN_V2) {
3097 				err = -EINVAL;
3098 				goto out;
3099 			}
3100 
3101 			if (le32_to_cpu(context->DataLength) <
3102 			    sizeof(durable_v2_blob->dcontext)) {
3103 				err = -EINVAL;
3104 				goto out;
3105 			}
3106 
3107 			durable_v2_blob =
3108 				(struct create_durable_req_v2 *)context;
3109 			ksmbd_debug(SMB, "Request for durable v2 open\n");
3110 			dh_info->fp = ksmbd_lookup_fd_cguid(durable_v2_blob->dcontext.CreateGuid);
3111 			if (dh_info->fp) {
3112 				if (!memcmp(conn->ClientGUID, dh_info->fp->client_guid,
3113 					    SMB2_CLIENT_GUID_SIZE)) {
3114 					if (!(req->hdr.Flags & SMB2_FLAGS_REPLAY_OPERATION)) {
3115 						err = -ENOEXEC;
3116 						ksmbd_put_durable_fd(dh_info->fp);
3117 						goto out;
3118 					}
3119 
3120 					if (dh_info->fp->conn) {
3121 						ksmbd_put_durable_fd(dh_info->fp);
3122 						err = -EBADF;
3123 						goto out;
3124 					}
3125 					dh_info->reconnected = true;
3126 					goto out;
3127 				}
3128 				ksmbd_put_durable_fd(dh_info->fp);
3129 				dh_info->fp = NULL;
3130 			}
3131 
3132 			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
3133 			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
3134 				dh_info->CreateGuid =
3135 					durable_v2_blob->dcontext.CreateGuid;
3136 				dh_info->persistent =
3137 					le32_to_cpu(durable_v2_blob->dcontext.Flags);
3138 				dh_info->timeout =
3139 					le32_to_cpu(durable_v2_blob->dcontext.Timeout);
3140 				dh_info->type = dh_idx;
3141 			}
3142 			break;
3143 		}
3144 		case DURABLE_REQ:
3145 			if (dh_info->type == DURABLE_RECONN)
3146 				goto out;
3147 			if (dh_info->type == DURABLE_RECONN_V2 ||
3148 			    dh_info->type == DURABLE_REQ_V2) {
3149 				err = -EINVAL;
3150 				goto out;
3151 			}
3152 
3153 			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
3154 			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
3155 				ksmbd_debug(SMB, "Request for durable open\n");
3156 				dh_info->type = dh_idx;
3157 			}
3158 		}
3159 	}
3160 
3161 out:
3162 	return err;
3163 }
3164 
3165 static int parse_app_instance_id(struct smb2_create_req *req,
3166 				 struct durable_info *dh_info)
3167 {
3168 	struct create_context *context;
3169 	char *data;
3170 
3171 	context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_ID,
3172 					 SMB2_CREATE_GUID_SIZE);
3173 	if (IS_ERR(context))
3174 		return PTR_ERR(context);
3175 	if (!context)
3176 		return 0;
3177 
3178 	if (le32_to_cpu(context->DataLength) < 20)
3179 		return -EINVAL;
3180 
3181 	data = (char *)context + le16_to_cpu(context->DataOffset);
3182 	if (data[0] != 20 || data[1])
3183 		return -EINVAL;
3184 
3185 	memcpy(dh_info->AppInstanceId, data + 4, SMB2_CREATE_GUID_SIZE);
3186 	dh_info->app_instance_id = true;
3187 	return 0;
3188 }
3189 
3190 /**
3191  * smb2_open() - handler for smb file open request
3192  * @work:	smb work containing request buffer
3193  *
3194  * Return:      0 on success, otherwise error
3195  */
3196 int smb2_open(struct ksmbd_work *work)
3197 {
3198 	struct ksmbd_conn *conn = work->conn;
3199 	struct ksmbd_session *sess = work->sess;
3200 	struct ksmbd_tree_connect *tcon = work->tcon;
3201 	struct smb2_create_req *req;
3202 	struct smb2_create_rsp *rsp;
3203 	struct path path;
3204 	struct ksmbd_share_config *share = tcon->share_conf;
3205 	struct ksmbd_file *fp = NULL;
3206 	struct file *filp = NULL;
3207 	struct mnt_idmap *idmap = NULL;
3208 	struct kstat stat;
3209 	struct create_context *context;
3210 	struct lease_ctx_info *lc = NULL;
3211 	struct create_ea_buf_req *ea_buf = NULL;
3212 	struct oplock_info *opinfo;
3213 	struct durable_info dh_info = {0};
3214 	__le32 *next_ptr = NULL;
3215 	int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
3216 	int rc = 0;
3217 	int contxt_cnt = 0, query_disk_id = 0;
3218 	bool maximal_access_ctxt = false, posix_ctxt = false;
3219 	int s_type = 0;
3220 	int next_off = 0;
3221 	char *name = NULL;
3222 	char *stream_name = NULL;
3223 	bool file_present = false, created = false, already_permitted = false;
3224 	int share_ret, need_truncate = 0;
3225 	u64 time, alloc_size = 0;
3226 	umode_t posix_mode = 0;
3227 	__le32 daccess, maximal_access = 0;
3228 	int iov_len = 0;
3229 
3230 	ksmbd_debug(SMB, "Received smb2 create request\n");
3231 
3232 	WORK_BUFFERS(work, req, rsp);
3233 
3234 	if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
3235 	    (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
3236 		ksmbd_debug(SMB, "invalid flag in chained command\n");
3237 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3238 		smb2_set_err_rsp(work);
3239 		return -EINVAL;
3240 	}
3241 
3242 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
3243 		ksmbd_debug(SMB, "IPC pipe create request\n");
3244 		return create_smb2_pipe(work);
3245 	}
3246 
3247 	if (req->CreateContextsOffset && tcon->posix_extensions) {
3248 		context = smb2_find_context_vals(req, SMB2_CREATE_TAG_POSIX, 16);
3249 		if (IS_ERR(context)) {
3250 			rc = PTR_ERR(context);
3251 			goto err_out2;
3252 		} else if (context) {
3253 			struct create_posix *posix = (struct create_posix *)context;
3254 
3255 			if (le16_to_cpu(context->DataOffset) +
3256 				le32_to_cpu(context->DataLength) <
3257 			    sizeof(struct create_posix) - 4) {
3258 				rc = -EINVAL;
3259 				goto err_out2;
3260 			}
3261 			ksmbd_debug(SMB, "get posix context\n");
3262 
3263 			posix_mode = le32_to_cpu(posix->Mode);
3264 			posix_ctxt = true;
3265 		}
3266 	}
3267 
3268 	if (req->NameLength) {
3269 		name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset),
3270 				     le16_to_cpu(req->NameLength),
3271 				     work->conn->local_nls);
3272 		if (IS_ERR(name)) {
3273 			rc = PTR_ERR(name);
3274 			name = NULL;
3275 			goto err_out2;
3276 		}
3277 
3278 		ksmbd_debug(SMB, "converted name = %s\n", name);
3279 
3280 		if (posix_ctxt == false) {
3281 			if (strchr(name, ':')) {
3282 				if (!test_share_config_flag(work->tcon->share_conf,
3283 							KSMBD_SHARE_FLAG_STREAMS)) {
3284 					rc = -EBADF;
3285 					goto err_out2;
3286 				}
3287 				rc = parse_stream_name(name, &stream_name, &s_type);
3288 				if (rc < 0)
3289 					goto err_out2;
3290 			}
3291 
3292 			rc = ksmbd_validate_filename(name);
3293 			if (rc < 0)
3294 				goto err_out2;
3295 		}
3296 
3297 		if (ksmbd_share_veto_filename(share, name)) {
3298 			rc = -ENOENT;
3299 			ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
3300 				    name);
3301 			goto err_out2;
3302 		}
3303 	} else {
3304 		name = kstrdup("", KSMBD_DEFAULT_GFP);
3305 		if (!name) {
3306 			rc = -ENOMEM;
3307 			goto err_out2;
3308 		}
3309 	}
3310 
3311 	req_op_level = req->RequestedOplockLevel;
3312 
3313 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
3314 	    req->CreateContextsOffset) {
3315 		lc = parse_lease_state(req);
3316 		if (IS_ERR(lc)) {
3317 			rc = PTR_ERR(lc);
3318 			lc = NULL;
3319 			goto err_out2;
3320 		}
3321 		if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
3322 			kfree(lc);
3323 			lc = NULL;
3324 			if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
3325 				req_op_level = SMB2_OPLOCK_LEVEL_NONE;
3326 		}
3327 		rc = parse_durable_handle_context(work, req, lc, &dh_info);
3328 		if (rc) {
3329 			ksmbd_debug(SMB, "error parsing durable handle context\n");
3330 			goto err_out2;
3331 		}
3332 		rc = parse_app_instance_id(req, &dh_info);
3333 		if (rc)
3334 			goto err_out2;
3335 
3336 		if (dh_info.reconnected == true) {
3337 			rc = smb2_check_durable_oplock(conn, share, dh_info.fp,
3338 					lc, sess->user, name);
3339 			if (rc)
3340 				goto err_out2;
3341 
3342 			rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
3343 			if (rc)
3344 				goto err_out2;
3345 
3346 			fp = dh_info.fp;
3347 
3348 			if (ksmbd_override_fsids(work)) {
3349 				rc = -ENOMEM;
3350 				goto err_out2;
3351 			}
3352 
3353 			file_info = FILE_OPENED;
3354 
3355 			rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
3356 			if (rc)
3357 				goto err_out2;
3358 
3359 			goto reconnected_fp;
3360 		}
3361 
3362 		if (dh_info.type == DURABLE_REQ_V2 && dh_info.app_instance_id)
3363 			ksmbd_close_fd_app_instance_id(dh_info.AppInstanceId);
3364 	} else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3365 		lc = parse_lease_state(req);
3366 		if (IS_ERR(lc)) {
3367 			rc = PTR_ERR(lc);
3368 			lc = NULL;
3369 			goto err_out2;
3370 		}
3371 		if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
3372 			kfree(lc);
3373 			lc = NULL;
3374 			req_op_level = SMB2_OPLOCK_LEVEL_NONE;
3375 		}
3376 	}
3377 
3378 	if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
3379 		pr_err("Invalid impersonationlevel : 0x%x\n",
3380 		       le32_to_cpu(req->ImpersonationLevel));
3381 		rc = -EIO;
3382 		rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
3383 		goto err_out2;
3384 	}
3385 
3386 	if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
3387 		pr_err("Invalid create options : 0x%x\n",
3388 		       le32_to_cpu(req->CreateOptions));
3389 		rc = -EINVAL;
3390 		goto err_out2;
3391 	} else {
3392 		if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
3393 		    req->CreateOptions & FILE_RANDOM_ACCESS_LE)
3394 			req->CreateOptions &= ~FILE_SEQUENTIAL_ONLY_LE;
3395 
3396 		if (req->CreateOptions &
3397 		    (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
3398 		     FILE_RESERVE_OPFILTER_LE)) {
3399 			rc = -EOPNOTSUPP;
3400 			goto err_out2;
3401 		}
3402 
3403 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3404 			if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
3405 				rc = -EINVAL;
3406 				goto err_out2;
3407 			} else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
3408 				req->CreateOptions &= ~FILE_NO_COMPRESSION_LE;
3409 			}
3410 		}
3411 	}
3412 
3413 	if (le32_to_cpu(req->CreateDisposition) >
3414 	    le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
3415 		pr_err("Invalid create disposition : 0x%x\n",
3416 		       le32_to_cpu(req->CreateDisposition));
3417 		rc = -EINVAL;
3418 		goto err_out2;
3419 	}
3420 
3421 	if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
3422 		pr_err("Invalid desired access : 0x%x\n",
3423 		       le32_to_cpu(req->DesiredAccess));
3424 		rc = -EACCES;
3425 		goto err_out2;
3426 	}
3427 
3428 	if (req->DesiredAccess == FILE_SYNCHRONIZE_LE &&
3429 	    req->CreateDisposition == FILE_OPEN_IF_LE &&
3430 	    !req->FileAttributes) {
3431 		rc = -EACCES;
3432 		goto err_out2;
3433 	}
3434 
3435 	if (req->FileAttributes &&
3436 	    (req->FileAttributes & ~cpu_to_le32(SMB2_CREATE_FILE_ATTRIBUTE_MASK))) {
3437 		pr_err("Invalid file attribute : 0x%x\n",
3438 		       le32_to_cpu(req->FileAttributes));
3439 		rc = -EINVAL;
3440 		goto err_out2;
3441 	}
3442 
3443 	if (req->CreateContextsOffset) {
3444 		/* Parse non-durable handle create contexts */
3445 		context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
3446 		if (IS_ERR(context)) {
3447 			rc = PTR_ERR(context);
3448 			goto err_out2;
3449 		} else if (context) {
3450 			ea_buf = (struct create_ea_buf_req *)context;
3451 			if (le16_to_cpu(context->DataOffset) +
3452 			    le32_to_cpu(context->DataLength) <
3453 			    sizeof(struct create_ea_buf_req)) {
3454 				rc = -EINVAL;
3455 				goto err_out2;
3456 			}
3457 			if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
3458 				rsp->hdr.Status = STATUS_ACCESS_DENIED;
3459 				rc = -EACCES;
3460 				goto err_out2;
3461 			}
3462 		}
3463 
3464 		context = smb2_find_context_vals(req,
3465 						 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
3466 		if (IS_ERR(context)) {
3467 			rc = PTR_ERR(context);
3468 			goto err_out2;
3469 		} else if (context) {
3470 			ksmbd_debug(SMB,
3471 				    "get query maximal access context\n");
3472 			maximal_access_ctxt = 1;
3473 		}
3474 
3475 		context = smb2_find_context_vals(req,
3476 						 SMB2_CREATE_TIMEWARP_REQUEST, 4);
3477 		if (IS_ERR(context)) {
3478 			rc = PTR_ERR(context);
3479 			goto err_out2;
3480 		} else if (context) {
3481 			ksmbd_debug(SMB, "get timewarp context\n");
3482 			rc = -EBADF;
3483 			goto err_out2;
3484 		}
3485 	}
3486 
3487 	if (ksmbd_override_fsids(work)) {
3488 		rc = -ENOMEM;
3489 		goto err_out2;
3490 	}
3491 
3492 	rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
3493 				 &path, 1);
3494 
3495 	/*
3496 	 * A durable handle opened with delete-on-close is preserved across a
3497 	 * disconnect so it can be reclaimed by a durable reconnect.  When a new
3498 	 * delete-on-close open for the same name arrives instead, the
3499 	 * disconnected handle must give way: close it so its delete-on-close
3500 	 * removes the file, then re-resolve so this open can create a fresh one.
3501 	 */
3502 	if (!rc && (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) &&
3503 	    (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
3504 	     req->CreateDisposition == FILE_OPEN_IF_LE) &&
3505 	    ksmbd_close_disconnected_durable_delete_on_close(path.dentry)) {
3506 		path_put(&path);
3507 		rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
3508 					 &path, 1);
3509 	}
3510 
3511 	if (!rc) {
3512 		file_present = true;
3513 
3514 		if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
3515 			/*
3516 			 * If file exists with under flags, return access
3517 			 * denied error.
3518 			 */
3519 			if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
3520 			    req->CreateDisposition == FILE_OPEN_IF_LE) {
3521 				rc = -EACCES;
3522 				goto err_out;
3523 			}
3524 
3525 			if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3526 				ksmbd_debug(SMB,
3527 					    "User does not have write permission\n");
3528 				rc = -EACCES;
3529 				goto err_out;
3530 			}
3531 		} else if (d_is_symlink(path.dentry)) {
3532 			rc = -EACCES;
3533 			goto err_out;
3534 		}
3535 
3536 		idmap = mnt_idmap(path.mnt);
3537 	} else {
3538 		if (rc != -ENOENT)
3539 			goto err_out;
3540 		ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
3541 			    name, rc);
3542 		rc = 0;
3543 	}
3544 
3545 	/*
3546 	 * An explicit ::$DATA suffix names the unnamed data stream and is
3547 	 * canonicalized to a NULL stream name (base file), but the request
3548 	 * still has to be validated against the data-stream type, e.g. opening
3549 	 * <dir>::$DATA with FILE_DIRECTORY_FILE must fail with
3550 	 * STATUS_NOT_A_DIRECTORY.
3551 	 */
3552 	if (stream_name || s_type == DATA_STREAM) {
3553 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3554 			if (s_type == DATA_STREAM) {
3555 				rc = -EIO;
3556 				rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3557 			}
3558 		} else {
3559 			if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
3560 			    s_type == DATA_STREAM) {
3561 				rc = -EIO;
3562 				rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3563 			}
3564 		}
3565 
3566 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
3567 		    req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
3568 			rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3569 			rc = -EIO;
3570 		}
3571 
3572 		if (rc < 0)
3573 			goto err_out;
3574 	}
3575 
3576 	if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
3577 	    S_ISDIR(d_inode(path.dentry)->i_mode) &&
3578 	    !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3579 		ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
3580 			    name, req->CreateOptions);
3581 		rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3582 		rc = -EIO;
3583 		goto err_out;
3584 	}
3585 
3586 	if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
3587 	    !(req->CreateDisposition == FILE_CREATE_LE) &&
3588 	    !S_ISDIR(d_inode(path.dentry)->i_mode)) {
3589 		rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3590 		rc = -EIO;
3591 		goto err_out;
3592 	}
3593 
3594 	if (!stream_name && file_present &&
3595 	    req->CreateDisposition == FILE_CREATE_LE) {
3596 		rc = -EEXIST;
3597 		goto err_out;
3598 	}
3599 
3600 	daccess = smb_map_generic_desired_access(req->DesiredAccess);
3601 
3602 	if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3603 		rc = smb_check_perm_dacl(conn, &path, &daccess,
3604 					 sess->user->uid);
3605 		if (rc)
3606 			goto err_out;
3607 	}
3608 
3609 	if (daccess & FILE_MAXIMAL_ACCESS_LE) {
3610 		if (!file_present) {
3611 			daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
3612 		} else {
3613 			ksmbd_vfs_query_maximal_access(idmap,
3614 							    path.dentry,
3615 							    &daccess);
3616 			already_permitted = true;
3617 		}
3618 		maximal_access = daccess;
3619 	}
3620 
3621 	open_flags = smb2_create_open_flags(file_present, daccess,
3622 					    req->CreateDisposition,
3623 					    &may_flags,
3624 					    req->CreateOptions,
3625 					    file_present ? d_inode(path.dentry)->i_mode : 0);
3626 
3627 	if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3628 		if (open_flags & (O_CREAT | O_TRUNC)) {
3629 			ksmbd_debug(SMB,
3630 				    "User does not have write permission\n");
3631 			rc = -EACCES;
3632 			goto err_out;
3633 		}
3634 	}
3635 
3636 	/*create file if not present */
3637 	if (!file_present) {
3638 		rc = smb2_creat(work, &path, name, open_flags,
3639 				posix_mode,
3640 				req->CreateOptions & FILE_DIRECTORY_FILE_LE);
3641 		if (rc) {
3642 			if (rc == -ENOENT) {
3643 				rc = -EIO;
3644 				rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3645 			}
3646 			goto err_out;
3647 		}
3648 
3649 		created = true;
3650 		idmap = mnt_idmap(path.mnt);
3651 		if (ea_buf) {
3652 			if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3653 			    sizeof(struct smb2_ea_info)) {
3654 				rc = -EINVAL;
3655 				goto err_out;
3656 			}
3657 
3658 			rc = smb2_set_ea(&ea_buf->ea,
3659 					 le32_to_cpu(ea_buf->ccontext.DataLength),
3660 					 &path, false);
3661 			if (rc == -EOPNOTSUPP)
3662 				rc = 0;
3663 			else if (rc)
3664 				goto err_out;
3665 		}
3666 	} else if (!already_permitted) {
3667 		/* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3668 		 * because execute(search) permission on a parent directory,
3669 		 * is already granted.
3670 		 */
3671 		if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3672 			rc = inode_permission(idmap,
3673 					      d_inode(path.dentry),
3674 					      may_flags);
3675 			if (rc)
3676 				goto err_out;
3677 
3678 			if ((daccess & FILE_DELETE_LE) ||
3679 			    (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3680 				rc = inode_permission(idmap,
3681 						      d_inode(path.dentry->d_parent),
3682 						      MAY_EXEC | MAY_WRITE);
3683 				if (rc)
3684 					goto err_out;
3685 			}
3686 		}
3687 	}
3688 
3689 	rc = ksmbd_query_inode_status(path.dentry->d_parent);
3690 	if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3691 		rc = -EBUSY;
3692 		goto err_out;
3693 	}
3694 
3695 	rc = 0;
3696 	filp = dentry_open(&path, open_flags, current_cred());
3697 	if (IS_ERR(filp)) {
3698 		rc = PTR_ERR(filp);
3699 		pr_err("dentry open for dir failed, rc %d\n", rc);
3700 		goto err_out;
3701 	}
3702 
3703 	if (file_present) {
3704 		if (!(open_flags & O_TRUNC))
3705 			file_info = FILE_OPENED;
3706 		else
3707 			file_info = FILE_OVERWRITTEN;
3708 
3709 		if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3710 		    FILE_SUPERSEDE_LE)
3711 			file_info = FILE_SUPERSEDED;
3712 	} else if (open_flags & O_CREAT) {
3713 		file_info = FILE_CREATED;
3714 	}
3715 
3716 	ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3717 
3718 	/* Obtain Volatile-ID */
3719 	fp = ksmbd_open_fd(work, filp);
3720 	if (IS_ERR(fp)) {
3721 		fput(filp);
3722 		rc = PTR_ERR(fp);
3723 		fp = NULL;
3724 		goto err_out;
3725 	}
3726 
3727 	/* Get Persistent-ID */
3728 	ksmbd_open_durable_fd(fp);
3729 	if (!has_file_id(fp->persistent_id)) {
3730 		rc = -ENOMEM;
3731 		goto err_out;
3732 	}
3733 
3734 	fp->cdoption = req->CreateDisposition;
3735 	fp->daccess = daccess;
3736 	fp->saccess = req->ShareAccess;
3737 	fp->coption = req->CreateOptions;
3738 
3739 	/* Set default windows and posix acls if creating new file */
3740 	if (created) {
3741 		int posix_acl_rc;
3742 		struct inode *inode = d_inode(path.dentry);
3743 
3744 		posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3745 							   &path,
3746 							   d_inode(path.dentry->d_parent));
3747 		if (posix_acl_rc)
3748 			ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3749 
3750 		rc = smb2_create_sd_buffer(work, req, &path);
3751 		if (rc && rc != -ENOENT)
3752 			goto err_out;
3753 
3754 		if (rc == -ENOENT) {
3755 			if (test_share_config_flag(work->tcon->share_conf,
3756 						   KSMBD_SHARE_FLAG_ACL_XATTR)) {
3757 				rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3758 						      sess->user->gid);
3759 			}
3760 			if (rc) {
3761 				if (posix_acl_rc)
3762 					ksmbd_vfs_set_init_posix_acl(idmap,
3763 								     &path);
3764 
3765 				if (test_share_config_flag(work->tcon->share_conf,
3766 							   KSMBD_SHARE_FLAG_ACL_XATTR)) {
3767 					struct smb_fattr fattr;
3768 					struct smb_ntsd *pntsd;
3769 					int pntsd_size;
3770 					size_t scratch_len;
3771 
3772 					ksmbd_acls_fattr(&fattr, idmap, inode);
3773 					scratch_len = smb_acl_sec_desc_scratch_len(&fattr,
3774 							NULL, 0,
3775 							OWNER_SECINFO | GROUP_SECINFO |
3776 							DACL_SECINFO);
3777 					if (!scratch_len || scratch_len == SIZE_MAX) {
3778 						rc = -EFBIG;
3779 						posix_acl_release(fattr.cf_acls);
3780 						posix_acl_release(fattr.cf_dacls);
3781 						goto err_out;
3782 					}
3783 
3784 					pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
3785 					if (!pntsd) {
3786 						rc = -ENOMEM;
3787 						posix_acl_release(fattr.cf_acls);
3788 						posix_acl_release(fattr.cf_dacls);
3789 						goto err_out;
3790 					}
3791 
3792 					rc = build_sec_desc(idmap,
3793 							    pntsd, NULL, 0,
3794 							    OWNER_SECINFO |
3795 							    GROUP_SECINFO |
3796 							    DACL_SECINFO,
3797 							    &pntsd_size, &fattr);
3798 					posix_acl_release(fattr.cf_acls);
3799 					posix_acl_release(fattr.cf_dacls);
3800 					if (rc) {
3801 						kvfree(pntsd);
3802 						goto err_out;
3803 					}
3804 
3805 					rc = ksmbd_vfs_set_sd_xattr(conn,
3806 								    idmap,
3807 								    &path,
3808 								    pntsd,
3809 								    pntsd_size,
3810 								    false);
3811 					kvfree(pntsd);
3812 					if (rc)
3813 						pr_err("failed to store ntacl in xattr : %d\n",
3814 						       rc);
3815 				}
3816 			}
3817 		}
3818 		rc = 0;
3819 	}
3820 
3821 	if (stream_name) {
3822 		rc = smb2_set_stream_name_xattr(&path,
3823 						fp,
3824 						stream_name,
3825 						s_type);
3826 		if (rc)
3827 			goto err_out;
3828 		file_info = FILE_CREATED;
3829 	}
3830 
3831 	fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3832 			FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3833 
3834 	fp->is_posix_ctxt = posix_ctxt;
3835 
3836 	/* fp should be searchable through ksmbd_inode.m_fp_list
3837 	 * after daccess, saccess, attrib_only, and stream are
3838 	 * initialized.
3839 	 */
3840 	down_write(&fp->f_ci->m_lock);
3841 	list_add(&fp->node, &fp->f_ci->m_fp_list);
3842 	up_write(&fp->f_ci->m_lock);
3843 
3844 	/* Check delete pending among previous fp before oplock break */
3845 	if (ksmbd_inode_pending_delete(fp)) {
3846 		rc = -EBUSY;
3847 		goto err_out;
3848 	}
3849 
3850 	if (!stream_name && daccess & FILE_DELETE_LE &&
3851 	    ksmbd_has_stream_without_delete_share(fp)) {
3852 		rc = -EPERM;
3853 		goto err_out;
3854 	}
3855 
3856 	if (file_present || created)
3857 		path_put(&path);
3858 
3859 	if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3860 	    !fp->attrib_only && !stream_name) {
3861 		smb_break_all_oplock(work, fp);
3862 		need_truncate = 1;
3863 	}
3864 
3865 	share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3866 	if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3867 	    (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3868 	     !(conn->vals->req_capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3869 		if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3870 			rc = share_ret;
3871 			goto err_out1;
3872 		}
3873 	} else {
3874 		if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && lc) {
3875 			if (S_ISDIR(file_inode(filp)->i_mode)) {
3876 				lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
3877 				lc->is_dir = true;
3878 			}
3879 
3880 			/*
3881 			 * Compare parent lease using parent key. If there is no
3882 			 * a lease that has same parent key, Send lease break
3883 			 * notification.
3884 			 */
3885 			smb_send_parent_lease_break_noti(fp, lc);
3886 
3887 			req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3888 			ksmbd_debug(SMB,
3889 				    "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3890 				    name, req_op_level, lc->req_state);
3891 			rc = find_same_lease_key(conn, fp->f_ci, lc);
3892 			if (rc)
3893 				goto err_out1;
3894 		} else if (open_flags == O_RDONLY &&
3895 			   (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3896 			    req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3897 			req_op_level = SMB2_OPLOCK_LEVEL_II;
3898 
3899 		rc = smb_grant_oplock(work, req_op_level,
3900 				      fp->persistent_id, fp,
3901 				      le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3902 				      lc, share_ret);
3903 		if (rc < 0)
3904 			goto err_out1;
3905 	}
3906 
3907 	if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
3908 		smb_break_all_levII_oplock_for_delete(work, fp);
3909 		ksmbd_fd_set_delete_on_close(fp, file_info);
3910 	}
3911 
3912 	if (need_truncate) {
3913 		rc = smb2_create_truncate(&fp->filp->f_path);
3914 		if (rc)
3915 			goto err_out1;
3916 	}
3917 
3918 	if (req->CreateContextsOffset) {
3919 		struct create_alloc_size_req *az_req;
3920 
3921 		az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3922 					SMB2_CREATE_ALLOCATION_SIZE, 4);
3923 		if (IS_ERR(az_req)) {
3924 			rc = PTR_ERR(az_req);
3925 			goto err_out1;
3926 		} else if (az_req) {
3927 			int err;
3928 
3929 			if (le16_to_cpu(az_req->ccontext.DataOffset) +
3930 			    le32_to_cpu(az_req->ccontext.DataLength) <
3931 			    sizeof(struct create_alloc_size_req)) {
3932 				rc = -EINVAL;
3933 				goto err_out1;
3934 			}
3935 			alloc_size = le64_to_cpu(az_req->AllocationSize);
3936 			ksmbd_debug(SMB,
3937 				    "request smb2 create allocate size : %llu\n",
3938 				    alloc_size);
3939 			smb_break_all_levII_oplock(work, fp, 1);
3940 			err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3941 					    alloc_size);
3942 			if (err < 0)
3943 				ksmbd_debug(SMB,
3944 					    "vfs_fallocate is failed : %d\n",
3945 					    err);
3946 		}
3947 
3948 		context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3949 		if (IS_ERR(context)) {
3950 			rc = PTR_ERR(context);
3951 			goto err_out1;
3952 		} else if (context) {
3953 			ksmbd_debug(SMB, "get query on disk id context\n");
3954 			query_disk_id = 1;
3955 		}
3956 
3957 		if (conn->is_aapl == false) {
3958 			context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
3959 			if (IS_ERR(context)) {
3960 				rc = PTR_ERR(context);
3961 				goto err_out1;
3962 			} else if (context)
3963 				conn->is_aapl = true;
3964 		}
3965 	}
3966 
3967 	rc = ksmbd_vfs_getattr(&path, &stat);
3968 	if (rc)
3969 		goto err_out1;
3970 
3971 	if (stat.result_mask & STATX_BTIME)
3972 		fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3973 	else
3974 		fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3975 	fp->change_time = ksmbd_UnixTimeToNT(stat.ctime);
3976 	fp->allocation_size = S_ISDIR(stat.mode) ? 0 :
3977 		(alloc_size ?: stat.blocks << 9);
3978 	if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3979 		fp->f_ci->m_fattr =
3980 			cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3981 
3982 	if (!created)
3983 		smb2_update_xattrs(tcon, &path, fp);
3984 
3985 	ksmbd_vfs_update_compressed_fattr(path.dentry, &fp->f_ci->m_fattr);
3986 
3987 	if (created)
3988 		smb2_new_xattrs(tcon, &path, fp);
3989 
3990 	memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3991 
3992 	if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
3993 		if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent &&
3994 		    test_share_config_flag(work->tcon->share_conf,
3995 					   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
3996 			fp->is_persistent = true;
3997 		else
3998 			fp->is_durable = true;
3999 
4000 		if (dh_info.type == DURABLE_REQ_V2) {
4001 			memcpy(fp->create_guid, dh_info.CreateGuid,
4002 					SMB2_CREATE_GUID_SIZE);
4003 			if (dh_info.app_instance_id)
4004 				memcpy(fp->app_instance_id,
4005 				       dh_info.AppInstanceId,
4006 				       SMB2_CREATE_GUID_SIZE);
4007 			if (dh_info.timeout)
4008 				fp->durable_timeout =
4009 					min_t(unsigned int, dh_info.timeout,
4010 					      DURABLE_HANDLE_MAX_TIMEOUT);
4011 			else
4012 				fp->durable_timeout = 60;
4013 		}
4014 	}
4015 
4016 reconnected_fp:
4017 	rsp->StructureSize = cpu_to_le16(89);
4018 	opinfo = opinfo_get(fp);
4019 	rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
4020 	rsp->Flags = 0;
4021 	rsp->CreateAction = cpu_to_le32(file_info);
4022 	rsp->CreationTime = cpu_to_le64(fp->create_time);
4023 	time = ksmbd_UnixTimeToNT(stat.atime);
4024 	rsp->LastAccessTime = cpu_to_le64(time);
4025 	time = ksmbd_UnixTimeToNT(stat.mtime);
4026 	fp->open_mtime = time;
4027 	rsp->LastWriteTime = cpu_to_le64(time);
4028 	rsp->ChangeTime = cpu_to_le64(fp->change_time);
4029 	/*
4030 	 * The cached allocation size hides filesystem rounding for the
4031 	 * requested allocation, but it can go stale when the file grows past
4032 	 * it via writes (e.g. across a durable reconnect). Refresh it once the
4033 	 * file exceeds the cached value, rounding the end of file up to the
4034 	 * volume allocation unit (the filesystem block size, matching the
4035 	 * SectorsPerAllocationUnit/BytesPerSector ksmbd advertises) rather than
4036 	 * using the raw on-disk block count, which can include filesystem
4037 	 * preallocation and metadata rounding.
4038 	 */
4039 	if (!S_ISDIR(stat.mode) && stat.size > fp->allocation_size)
4040 		fp->allocation_size = round_up(stat.size, stat.blksize);
4041 	rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
4042 	rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4043 	rsp->FileAttributes = fp->f_ci->m_fattr;
4044 
4045 	rsp->Reserved2 = 0;
4046 
4047 	rsp->PersistentFileId = fp->persistent_id;
4048 	rsp->VolatileFileId = fp->volatile_id;
4049 
4050 	rsp->CreateContextsOffset = 0;
4051 	rsp->CreateContextsLength = 0;
4052 	iov_len = offsetof(struct smb2_create_rsp, Buffer);
4053 
4054 	/* If lease is request send lease context response */
4055 	if (opinfo && opinfo->is_lease) {
4056 		struct create_context *lease_ccontext;
4057 
4058 		ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
4059 			    name, opinfo->o_lease->state);
4060 		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
4061 
4062 		lease_ccontext = (struct create_context *)rsp->Buffer;
4063 		contxt_cnt++;
4064 		create_lease_buf(rsp->Buffer, opinfo->o_lease);
4065 		le32_add_cpu(&rsp->CreateContextsLength,
4066 			     conn->vals->create_lease_size);
4067 		iov_len += conn->vals->create_lease_size;
4068 		next_ptr = &lease_ccontext->Next;
4069 		next_off = conn->vals->create_lease_size;
4070 	}
4071 	opinfo_put(opinfo);
4072 
4073 	if (maximal_access_ctxt) {
4074 		struct create_context *mxac_ccontext;
4075 
4076 		if (maximal_access == 0)
4077 			ksmbd_vfs_query_maximal_access(idmap,
4078 						       path.dentry,
4079 						       &maximal_access);
4080 		mxac_ccontext = (struct create_context *)(rsp->Buffer +
4081 				le32_to_cpu(rsp->CreateContextsLength));
4082 		contxt_cnt++;
4083 		create_mxac_rsp_buf(rsp->Buffer +
4084 				le32_to_cpu(rsp->CreateContextsLength),
4085 				le32_to_cpu(maximal_access));
4086 		le32_add_cpu(&rsp->CreateContextsLength,
4087 			     conn->vals->create_mxac_size);
4088 		iov_len += conn->vals->create_mxac_size;
4089 		if (next_ptr)
4090 			*next_ptr = cpu_to_le32(next_off);
4091 		next_ptr = &mxac_ccontext->Next;
4092 		next_off = conn->vals->create_mxac_size;
4093 	}
4094 
4095 	if (query_disk_id) {
4096 		struct create_context *disk_id_ccontext;
4097 
4098 		disk_id_ccontext = (struct create_context *)(rsp->Buffer +
4099 				le32_to_cpu(rsp->CreateContextsLength));
4100 		contxt_cnt++;
4101 		create_disk_id_rsp_buf(rsp->Buffer +
4102 				le32_to_cpu(rsp->CreateContextsLength),
4103 				stat.ino, tcon->id);
4104 		le32_add_cpu(&rsp->CreateContextsLength,
4105 			     conn->vals->create_disk_id_size);
4106 		iov_len += conn->vals->create_disk_id_size;
4107 		if (next_ptr)
4108 			*next_ptr = cpu_to_le32(next_off);
4109 		next_ptr = &disk_id_ccontext->Next;
4110 		next_off = conn->vals->create_disk_id_size;
4111 	}
4112 
4113 	if (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2) {
4114 		struct create_context *durable_ccontext;
4115 
4116 		durable_ccontext = (struct create_context *)(rsp->Buffer +
4117 				le32_to_cpu(rsp->CreateContextsLength));
4118 		contxt_cnt++;
4119 		if (dh_info.type == DURABLE_REQ) {
4120 			create_durable_rsp_buf(rsp->Buffer +
4121 					le32_to_cpu(rsp->CreateContextsLength));
4122 			le32_add_cpu(&rsp->CreateContextsLength,
4123 					conn->vals->create_durable_size);
4124 			iov_len += conn->vals->create_durable_size;
4125 		} else {
4126 			create_durable_v2_rsp_buf(rsp->Buffer +
4127 					le32_to_cpu(rsp->CreateContextsLength),
4128 					fp);
4129 			le32_add_cpu(&rsp->CreateContextsLength,
4130 					conn->vals->create_durable_v2_size);
4131 			iov_len += conn->vals->create_durable_v2_size;
4132 		}
4133 
4134 		if (next_ptr)
4135 			*next_ptr = cpu_to_le32(next_off);
4136 		next_ptr = &durable_ccontext->Next;
4137 		next_off = conn->vals->create_durable_size;
4138 	}
4139 
4140 	if (posix_ctxt) {
4141 		contxt_cnt++;
4142 		create_posix_rsp_buf(rsp->Buffer +
4143 				le32_to_cpu(rsp->CreateContextsLength),
4144 				fp);
4145 		le32_add_cpu(&rsp->CreateContextsLength,
4146 			     conn->vals->create_posix_size);
4147 		iov_len += conn->vals->create_posix_size;
4148 		if (next_ptr)
4149 			*next_ptr = cpu_to_le32(next_off);
4150 	}
4151 
4152 	if (contxt_cnt > 0) {
4153 		rsp->CreateContextsOffset =
4154 			cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
4155 	}
4156 
4157 err_out:
4158 	if (rc && (file_present || created))
4159 		path_put(&path);
4160 
4161 err_out1:
4162 	ksmbd_revert_fsids(work);
4163 
4164 err_out2:
4165 	if (!rc) {
4166 		rc = ksmbd_update_fstate(&work->sess->file_table, fp,
4167 					 FP_INITED);
4168 		if (!rc)
4169 			rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
4170 	}
4171 	if (rc) {
4172 		if (rc == -EINVAL)
4173 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4174 		else if (rc == -EOPNOTSUPP)
4175 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
4176 		else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
4177 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
4178 		else if (rc == -ENOENT)
4179 			rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
4180 		else if (rc == -EPERM)
4181 			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
4182 		else if (rc == -EBUSY)
4183 			rsp->hdr.Status = STATUS_DELETE_PENDING;
4184 		else if (rc == -EBADF)
4185 			rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
4186 		else if (rc == -ENOEXEC)
4187 			rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
4188 		else if (rc == -ENXIO)
4189 			rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
4190 		else if (rc == -EEXIST)
4191 			rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
4192 		else if (rc == -EMFILE)
4193 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
4194 		if (!rsp->hdr.Status)
4195 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4196 
4197 		if (fp)
4198 			ksmbd_fd_put(work, fp);
4199 		smb2_set_err_rsp(work);
4200 		ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
4201 	}
4202 
4203 	if (dh_info.reconnected) {
4204 		/*
4205 		 * If reconnect succeeded, fp was republished in the
4206 		 * session file table.  On a later error, ksmbd_fd_put()
4207 		 * above drops the session reference; drop the durable
4208 		 * lookup reference through the same session-aware path so
4209 		 * final close removes the volatile id before freeing fp.
4210 		 */
4211 		if (rc && fp == dh_info.fp)
4212 			ksmbd_fd_put(work, dh_info.fp);
4213 		else
4214 			ksmbd_put_durable_fd(dh_info.fp);
4215 	}
4216 
4217 	kfree(name);
4218 	kfree(lc);
4219 
4220 	return rc;
4221 }
4222 
4223 static int readdir_info_level_struct_sz(int info_level)
4224 {
4225 	switch (info_level) {
4226 	case FILE_FULL_DIRECTORY_INFORMATION:
4227 		return sizeof(FILE_FULL_DIRECTORY_INFO);
4228 	case FILE_BOTH_DIRECTORY_INFORMATION:
4229 		return sizeof(FILE_BOTH_DIRECTORY_INFO);
4230 	case FILE_DIRECTORY_INFORMATION:
4231 		return sizeof(FILE_DIRECTORY_INFO);
4232 	case FILE_NAMES_INFORMATION:
4233 		return sizeof(struct file_names_info);
4234 	case FILEID_FULL_DIRECTORY_INFORMATION:
4235 		return sizeof(FILE_ID_FULL_DIR_INFO);
4236 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4237 		return sizeof(struct file_id_both_directory_info);
4238 	case SMB_FIND_FILE_POSIX_INFO:
4239 		return sizeof(struct smb2_posix_info);
4240 	default:
4241 		return -EOPNOTSUPP;
4242 	}
4243 }
4244 
4245 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
4246 {
4247 	switch (info_level) {
4248 	case FILE_FULL_DIRECTORY_INFORMATION:
4249 	{
4250 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
4251 
4252 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->rptr;
4253 		d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
4254 		d_info->name = ffdinfo->FileName;
4255 		d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
4256 		return 0;
4257 	}
4258 	case FILE_BOTH_DIRECTORY_INFORMATION:
4259 	{
4260 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
4261 
4262 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->rptr;
4263 		d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
4264 		d_info->name = fbdinfo->FileName;
4265 		d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
4266 		return 0;
4267 	}
4268 	case FILE_DIRECTORY_INFORMATION:
4269 	{
4270 		FILE_DIRECTORY_INFO *fdinfo;
4271 
4272 		fdinfo = (FILE_DIRECTORY_INFO *)d_info->rptr;
4273 		d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
4274 		d_info->name = fdinfo->FileName;
4275 		d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
4276 		return 0;
4277 	}
4278 	case FILE_NAMES_INFORMATION:
4279 	{
4280 		struct file_names_info *fninfo;
4281 
4282 		fninfo = (struct file_names_info *)d_info->rptr;
4283 		d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
4284 		d_info->name = fninfo->FileName;
4285 		d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
4286 		return 0;
4287 	}
4288 	case FILEID_FULL_DIRECTORY_INFORMATION:
4289 	{
4290 		FILE_ID_FULL_DIR_INFO *dinfo;
4291 
4292 		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->rptr;
4293 		d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
4294 		d_info->name = dinfo->FileName;
4295 		d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
4296 		return 0;
4297 	}
4298 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4299 	{
4300 		struct file_id_both_directory_info *fibdinfo;
4301 
4302 		fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
4303 		d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
4304 		d_info->name = fibdinfo->FileName;
4305 		d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
4306 		return 0;
4307 	}
4308 	case SMB_FIND_FILE_POSIX_INFO:
4309 	{
4310 		struct smb2_posix_info *posix_info;
4311 
4312 		posix_info = (struct smb2_posix_info *)d_info->rptr;
4313 		d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
4314 		d_info->name = posix_info->name;
4315 		d_info->name_len = le32_to_cpu(posix_info->name_len);
4316 		return 0;
4317 	}
4318 	default:
4319 		return -EINVAL;
4320 	}
4321 }
4322 
4323 /**
4324  * smb2_populate_readdir_entry() - encode directory entry in smb2 response
4325  * buffer
4326  * @conn:	connection instance
4327  * @info_level:	smb information level
4328  * @d_info:	structure included variables for query dir
4329  * @ksmbd_kstat:	ksmbd wrapper of dirent stat information
4330  *
4331  * if directory has many entries, find first can't read it fully.
4332  * find next might be called multiple times to read remaining dir entries
4333  *
4334  * Return:	0 on success, otherwise error
4335  */
4336 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
4337 				       struct ksmbd_dir_info *d_info,
4338 				       struct ksmbd_kstat *ksmbd_kstat)
4339 {
4340 	int next_entry_offset = 0;
4341 	char *conv_name;
4342 	int conv_len;
4343 	void *kstat;
4344 	int struct_sz, rc = 0;
4345 
4346 	conv_name = ksmbd_convert_dir_info_name(d_info,
4347 						conn->local_nls,
4348 						&conv_len);
4349 	if (!conv_name)
4350 		return -ENOMEM;
4351 
4352 	/* Somehow the name has only terminating NULL bytes */
4353 	if (conv_len < 0) {
4354 		rc = -EINVAL;
4355 		goto free_conv_name;
4356 	}
4357 
4358 	struct_sz = readdir_info_level_struct_sz(info_level);
4359 	if (struct_sz == -EOPNOTSUPP) {
4360 		rc = -EINVAL;
4361 		goto free_conv_name;
4362 	}
4363 
4364 	struct_sz += conv_len;
4365 	next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
4366 	d_info->last_entry_off_align = next_entry_offset - struct_sz;
4367 
4368 	if (next_entry_offset > d_info->out_buf_len) {
4369 		d_info->out_buf_len = 0;
4370 		rc = -ENOSPC;
4371 		goto free_conv_name;
4372 	}
4373 
4374 	kstat = d_info->wptr;
4375 	if (info_level != FILE_NAMES_INFORMATION)
4376 		kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
4377 
4378 	switch (info_level) {
4379 	case FILE_FULL_DIRECTORY_INFORMATION:
4380 	{
4381 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
4382 
4383 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)kstat;
4384 		ffdinfo->FileNameLength = cpu_to_le32(conv_len);
4385 		ffdinfo->EaSize =
4386 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4387 		if (ffdinfo->EaSize)
4388 			ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4389 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4390 			ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4391 		memcpy(ffdinfo->FileName, conv_name, conv_len);
4392 		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4393 		break;
4394 	}
4395 	case FILE_BOTH_DIRECTORY_INFORMATION:
4396 	{
4397 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
4398 
4399 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)kstat;
4400 		fbdinfo->FileNameLength = cpu_to_le32(conv_len);
4401 		fbdinfo->EaSize =
4402 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4403 		if (fbdinfo->EaSize)
4404 			fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4405 		fbdinfo->ShortNameLength = 0;
4406 		fbdinfo->Reserved = 0;
4407 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4408 			fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4409 		memcpy(fbdinfo->FileName, conv_name, conv_len);
4410 		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4411 		break;
4412 	}
4413 	case FILE_DIRECTORY_INFORMATION:
4414 	{
4415 		FILE_DIRECTORY_INFO *fdinfo;
4416 
4417 		fdinfo = (FILE_DIRECTORY_INFO *)kstat;
4418 		fdinfo->FileNameLength = cpu_to_le32(conv_len);
4419 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4420 			fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4421 		memcpy(fdinfo->FileName, conv_name, conv_len);
4422 		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4423 		break;
4424 	}
4425 	case FILE_NAMES_INFORMATION:
4426 	{
4427 		struct file_names_info *fninfo;
4428 
4429 		fninfo = (struct file_names_info *)kstat;
4430 		fninfo->FileNameLength = cpu_to_le32(conv_len);
4431 		memcpy(fninfo->FileName, conv_name, conv_len);
4432 		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4433 		break;
4434 	}
4435 	case FILEID_FULL_DIRECTORY_INFORMATION:
4436 	{
4437 		FILE_ID_FULL_DIR_INFO *dinfo;
4438 
4439 		dinfo = (FILE_ID_FULL_DIR_INFO *)kstat;
4440 		dinfo->FileNameLength = cpu_to_le32(conv_len);
4441 		dinfo->EaSize =
4442 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4443 		if (dinfo->EaSize)
4444 			dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4445 		dinfo->Reserved = 0;
4446 		if (conn->is_aapl)
4447 			dinfo->UniqueId = 0;
4448 		else
4449 			dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4450 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4451 			dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4452 		memcpy(dinfo->FileName, conv_name, conv_len);
4453 		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4454 		break;
4455 	}
4456 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4457 	{
4458 		struct file_id_both_directory_info *fibdinfo;
4459 
4460 		fibdinfo = (struct file_id_both_directory_info *)kstat;
4461 		fibdinfo->FileNameLength = cpu_to_le32(conv_len);
4462 		fibdinfo->EaSize =
4463 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4464 		if (fibdinfo->EaSize)
4465 			fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4466 		if (conn->is_aapl)
4467 			fibdinfo->UniqueId = 0;
4468 		else
4469 			fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4470 		fibdinfo->ShortNameLength = 0;
4471 		fibdinfo->Reserved = 0;
4472 		fibdinfo->Reserved2 = cpu_to_le16(0);
4473 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4474 			fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4475 		memcpy(fibdinfo->FileName, conv_name, conv_len);
4476 		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4477 		break;
4478 	}
4479 	case SMB_FIND_FILE_POSIX_INFO:
4480 	{
4481 		struct smb2_posix_info *posix_info;
4482 		u64 time;
4483 
4484 		posix_info = (struct smb2_posix_info *)kstat;
4485 		posix_info->Ignored = 0;
4486 		posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
4487 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
4488 		posix_info->ChangeTime = cpu_to_le64(time);
4489 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
4490 		posix_info->LastAccessTime = cpu_to_le64(time);
4491 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
4492 		posix_info->LastWriteTime = cpu_to_le64(time);
4493 		posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
4494 		posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
4495 		posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
4496 		posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
4497 		posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
4498 		switch (ksmbd_kstat->kstat->mode & S_IFMT) {
4499 		case S_IFDIR:
4500 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
4501 			break;
4502 		case S_IFLNK:
4503 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
4504 			break;
4505 		case S_IFCHR:
4506 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
4507 			break;
4508 		case S_IFBLK:
4509 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
4510 			break;
4511 		case S_IFIFO:
4512 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
4513 			break;
4514 		case S_IFSOCK:
4515 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
4516 		}
4517 
4518 		posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
4519 		posix_info->DosAttributes =
4520 			S_ISDIR(ksmbd_kstat->kstat->mode) ?
4521 				FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
4522 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4523 			posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4524 		/*
4525 		 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4526 		 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4527 		 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
4528 		 */
4529 		id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
4530 			  SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
4531 		id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
4532 			  SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
4533 		memcpy(posix_info->name, conv_name, conv_len);
4534 		posix_info->name_len = cpu_to_le32(conv_len);
4535 		posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
4536 		break;
4537 	}
4538 
4539 	} /* switch (info_level) */
4540 
4541 	d_info->last_entry_offset = d_info->data_count;
4542 	d_info->data_count += next_entry_offset;
4543 	d_info->out_buf_len -= next_entry_offset;
4544 	d_info->wptr += next_entry_offset;
4545 
4546 	ksmbd_debug(SMB,
4547 		    "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
4548 		    info_level, d_info->out_buf_len,
4549 		    next_entry_offset, d_info->data_count);
4550 
4551 free_conv_name:
4552 	kfree(conv_name);
4553 	return rc;
4554 }
4555 
4556 struct smb2_query_dir_private {
4557 	struct ksmbd_work	*work;
4558 	char			*search_pattern;
4559 	struct ksmbd_file	*dir_fp;
4560 
4561 	struct ksmbd_dir_info	*d_info;
4562 	int			info_level;
4563 };
4564 
4565 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
4566 {
4567 	struct mnt_idmap	*idmap = file_mnt_idmap(priv->dir_fp->filp);
4568 	struct kstat		kstat;
4569 	struct ksmbd_kstat	ksmbd_kstat;
4570 	int			rc;
4571 	int			i;
4572 
4573 	for (i = 0; i < priv->d_info->num_entry; i++) {
4574 		struct dentry *dent;
4575 
4576 		if (dentry_name(priv->d_info, priv->info_level))
4577 			return -EINVAL;
4578 
4579 		dent = lookup_one_unlocked(idmap,
4580 					   &QSTR_LEN(priv->d_info->name,
4581 						     priv->d_info->name_len),
4582 					   priv->dir_fp->filp->f_path.dentry);
4583 
4584 		if (IS_ERR(dent)) {
4585 			ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
4586 				    priv->d_info->name,
4587 				    PTR_ERR(dent));
4588 			continue;
4589 		}
4590 		if (unlikely(d_is_negative(dent))) {
4591 			dput(dent);
4592 			ksmbd_debug(SMB, "Negative dentry `%s'\n",
4593 				    priv->d_info->name);
4594 			continue;
4595 		}
4596 
4597 		ksmbd_kstat.kstat = &kstat;
4598 		if (priv->info_level != FILE_NAMES_INFORMATION) {
4599 			rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
4600 							 idmap,
4601 							 dent,
4602 							 &ksmbd_kstat);
4603 			if (rc) {
4604 				dput(dent);
4605 				continue;
4606 			}
4607 		}
4608 
4609 		rc = smb2_populate_readdir_entry(priv->work->conn,
4610 						 priv->info_level,
4611 						 priv->d_info,
4612 						 &ksmbd_kstat);
4613 		dput(dent);
4614 		if (rc)
4615 			return rc;
4616 	}
4617 	return 0;
4618 }
4619 
4620 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
4621 				   int info_level)
4622 {
4623 	int struct_sz;
4624 	int conv_len;
4625 	int next_entry_offset;
4626 
4627 	struct_sz = readdir_info_level_struct_sz(info_level);
4628 	if (struct_sz == -EOPNOTSUPP)
4629 		return -EOPNOTSUPP;
4630 
4631 	conv_len = (d_info->name_len + 1) * 2;
4632 	next_entry_offset = ALIGN(struct_sz + conv_len,
4633 				  KSMBD_DIR_INFO_ALIGNMENT);
4634 
4635 	if (next_entry_offset > d_info->out_buf_len) {
4636 		d_info->out_buf_len = 0;
4637 		return -ENOSPC;
4638 	}
4639 
4640 	switch (info_level) {
4641 	case FILE_FULL_DIRECTORY_INFORMATION:
4642 	{
4643 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
4644 
4645 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->wptr;
4646 		memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
4647 		ffdinfo->FileName[d_info->name_len] = 0x00;
4648 		ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4649 		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4650 		break;
4651 	}
4652 	case FILE_BOTH_DIRECTORY_INFORMATION:
4653 	{
4654 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
4655 
4656 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->wptr;
4657 		memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
4658 		fbdinfo->FileName[d_info->name_len] = 0x00;
4659 		fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4660 		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4661 		break;
4662 	}
4663 	case FILE_DIRECTORY_INFORMATION:
4664 	{
4665 		FILE_DIRECTORY_INFO *fdinfo;
4666 
4667 		fdinfo = (FILE_DIRECTORY_INFO *)d_info->wptr;
4668 		memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
4669 		fdinfo->FileName[d_info->name_len] = 0x00;
4670 		fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4671 		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4672 		break;
4673 	}
4674 	case FILE_NAMES_INFORMATION:
4675 	{
4676 		struct file_names_info *fninfo;
4677 
4678 		fninfo = (struct file_names_info *)d_info->wptr;
4679 		memcpy(fninfo->FileName, d_info->name, d_info->name_len);
4680 		fninfo->FileName[d_info->name_len] = 0x00;
4681 		fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
4682 		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4683 		break;
4684 	}
4685 	case FILEID_FULL_DIRECTORY_INFORMATION:
4686 	{
4687 		FILE_ID_FULL_DIR_INFO *dinfo;
4688 
4689 		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->wptr;
4690 		memcpy(dinfo->FileName, d_info->name, d_info->name_len);
4691 		dinfo->FileName[d_info->name_len] = 0x00;
4692 		dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4693 		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4694 		break;
4695 	}
4696 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4697 	{
4698 		struct file_id_both_directory_info *fibdinfo;
4699 
4700 		fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
4701 		memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
4702 		fibdinfo->FileName[d_info->name_len] = 0x00;
4703 		fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4704 		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4705 		break;
4706 	}
4707 	case SMB_FIND_FILE_POSIX_INFO:
4708 	{
4709 		struct smb2_posix_info *posix_info;
4710 
4711 		posix_info = (struct smb2_posix_info *)d_info->wptr;
4712 		memcpy(posix_info->name, d_info->name, d_info->name_len);
4713 		posix_info->name[d_info->name_len] = 0x00;
4714 		posix_info->name_len = cpu_to_le32(d_info->name_len);
4715 		posix_info->NextEntryOffset =
4716 			cpu_to_le32(next_entry_offset);
4717 		break;
4718 	}
4719 	} /* switch (info_level) */
4720 
4721 	d_info->num_entry++;
4722 	d_info->out_buf_len -= next_entry_offset;
4723 	d_info->wptr += next_entry_offset;
4724 	return 0;
4725 }
4726 
4727 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
4728 		       loff_t offset, u64 ino, unsigned int d_type)
4729 {
4730 	struct ksmbd_readdir_data	*buf;
4731 	struct smb2_query_dir_private	*priv;
4732 	struct ksmbd_dir_info		*d_info;
4733 	int				rc;
4734 
4735 	buf	= container_of(ctx, struct ksmbd_readdir_data, ctx);
4736 	priv	= buf->private;
4737 	d_info	= priv->d_info;
4738 
4739 	/* dot and dotdot entries are already reserved */
4740 	if (!strcmp(".", name) || !strcmp("..", name))
4741 		return true;
4742 	d_info->num_scan++;
4743 	if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
4744 		return true;
4745 	if (!match_pattern(name, namlen, priv->search_pattern))
4746 		return true;
4747 
4748 	d_info->name		= name;
4749 	d_info->name_len	= namlen;
4750 	rc = reserve_populate_dentry(d_info, priv->info_level);
4751 	if (rc)
4752 		return false;
4753 	if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
4754 		d_info->out_buf_len = 0;
4755 	return true;
4756 }
4757 
4758 static int verify_info_level(int info_level)
4759 {
4760 	switch (info_level) {
4761 	case FILE_FULL_DIRECTORY_INFORMATION:
4762 	case FILE_BOTH_DIRECTORY_INFORMATION:
4763 	case FILE_DIRECTORY_INFORMATION:
4764 	case FILE_NAMES_INFORMATION:
4765 	case FILEID_FULL_DIRECTORY_INFORMATION:
4766 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4767 	case SMB_FIND_FILE_POSIX_INFO:
4768 		break;
4769 	default:
4770 		return -EOPNOTSUPP;
4771 	}
4772 
4773 	return 0;
4774 }
4775 
4776 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
4777 {
4778 	int free_len;
4779 
4780 	free_len = (int)(work->response_sz -
4781 		(get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
4782 	return free_len;
4783 }
4784 
4785 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
4786 				     unsigned short hdr2_len,
4787 				     unsigned int out_buf_len)
4788 {
4789 	int free_len;
4790 
4791 	if (out_buf_len > work->conn->vals->max_trans_size)
4792 		return -EINVAL;
4793 
4794 	free_len = smb2_resp_buf_len(work, hdr2_len);
4795 	if (free_len < 0)
4796 		return -EINVAL;
4797 
4798 	return min_t(int, out_buf_len, free_len);
4799 }
4800 
4801 int smb2_query_dir(struct ksmbd_work *work)
4802 {
4803 	struct ksmbd_conn *conn = work->conn;
4804 	struct smb2_query_directory_req *req;
4805 	struct smb2_query_directory_rsp *rsp;
4806 	struct ksmbd_share_config *share = work->tcon->share_conf;
4807 	struct ksmbd_file *dir_fp = NULL;
4808 	struct ksmbd_dir_info d_info;
4809 	int rc = 0;
4810 	char *srch_ptr = NULL;
4811 	unsigned char srch_flag;
4812 	int buffer_sz;
4813 	struct smb2_query_dir_private query_dir_private = {NULL, };
4814 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4815 
4816 	ksmbd_debug(SMB, "Received smb2 query directory request\n");
4817 
4818 	WORK_BUFFERS(work, req, rsp);
4819 
4820 	if (smb2_compound_has_failed(work, &rsp->hdr))
4821 		return -EACCES;
4822 
4823 	if (work->next_smb2_rcv_hdr_off &&
4824 	    !has_file_id(req->VolatileFileId)) {
4825 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4826 			    work->compound_fid);
4827 		id = work->compound_fid;
4828 		pid = work->compound_pfid;
4829 	}
4830 
4831 	if (!has_file_id(id)) {
4832 		id = req->VolatileFileId;
4833 		pid = req->PersistentFileId;
4834 	}
4835 
4836 	if (ksmbd_override_fsids(work)) {
4837 		rsp->hdr.Status = STATUS_NO_MEMORY;
4838 		smb2_set_err_rsp(work);
4839 		return -ENOMEM;
4840 	}
4841 
4842 	rc = verify_info_level(req->FileInformationClass);
4843 	if (rc) {
4844 		rc = -EFAULT;
4845 		goto err_out2;
4846 	}
4847 
4848 	dir_fp = ksmbd_lookup_fd_slow(work, id, pid);
4849 	if (!dir_fp) {
4850 		rc = -EBADF;
4851 		goto err_out2;
4852 	}
4853 
4854 	if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4855 	    inode_permission(file_mnt_idmap(dir_fp->filp),
4856 			     file_inode(dir_fp->filp),
4857 			     MAY_READ | MAY_EXEC)) {
4858 		pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4859 		rc = -EACCES;
4860 		goto err_out2;
4861 	}
4862 
4863 	if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4864 		pr_err("can't do query dir for a file\n");
4865 		rc = -EINVAL;
4866 		goto err_out2;
4867 	}
4868 
4869 	srch_flag = req->Flags;
4870 	srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
4871 					  le16_to_cpu(req->FileNameLength), 1,
4872 					  conn->local_nls);
4873 	if (IS_ERR(srch_ptr)) {
4874 		ksmbd_debug(SMB, "Search Pattern not found\n");
4875 		rc = -EINVAL;
4876 		goto err_out2;
4877 	} else {
4878 		ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4879 	}
4880 
4881 	mutex_lock(&dir_fp->readdir_lock);
4882 
4883 	if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4884 		ksmbd_debug(SMB, "Restart directory scan\n");
4885 		generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4886 	}
4887 
4888 	memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4889 	d_info.wptr = (char *)rsp->Buffer;
4890 	d_info.rptr = (char *)rsp->Buffer;
4891 	d_info.out_buf_len =
4892 		smb2_calc_max_out_buf_len(work,
4893 				offsetof(struct smb2_query_directory_rsp, Buffer),
4894 				le32_to_cpu(req->OutputBufferLength));
4895 	if (d_info.out_buf_len < 0) {
4896 		rc = -EINVAL;
4897 		goto err_out;
4898 	}
4899 	d_info.flags = srch_flag;
4900 
4901 	/*
4902 	 * reserve dot and dotdot entries in head of buffer
4903 	 * in first response
4904 	 */
4905 	rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4906 					       dir_fp, &d_info, srch_ptr,
4907 					       smb2_populate_readdir_entry);
4908 	if (rc == -ENOSPC)
4909 		rc = 0;
4910 	else if (rc)
4911 		goto err_out;
4912 
4913 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4914 		d_info.hide_dot_file = true;
4915 
4916 	buffer_sz				= d_info.out_buf_len;
4917 	d_info.rptr				= d_info.wptr;
4918 	query_dir_private.work			= work;
4919 	query_dir_private.search_pattern	= srch_ptr;
4920 	query_dir_private.dir_fp		= dir_fp;
4921 	query_dir_private.d_info		= &d_info;
4922 	query_dir_private.info_level		= req->FileInformationClass;
4923 	dir_fp->readdir_data.private		= &query_dir_private;
4924 	set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4925 again:
4926 	d_info.num_scan = 0;
4927 	rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4928 	/*
4929 	 * num_entry can be 0 if the directory iteration stops before reaching
4930 	 * the end of the directory and no file is matched with the search
4931 	 * pattern.
4932 	 */
4933 	if (rc >= 0 && !d_info.num_entry && d_info.num_scan &&
4934 	    d_info.out_buf_len > 0)
4935 		goto again;
4936 	/*
4937 	 * req->OutputBufferLength is too small to contain even one entry.
4938 	 * In this case, it immediately returns OutputBufferLength 0 to client.
4939 	 */
4940 	if (!d_info.out_buf_len && !d_info.num_entry)
4941 		goto no_buf_len;
4942 	if (rc > 0 || rc == -ENOSPC)
4943 		rc = 0;
4944 	else if (rc)
4945 		goto err_out;
4946 
4947 	d_info.wptr = d_info.rptr;
4948 	d_info.out_buf_len = buffer_sz;
4949 	rc = process_query_dir_entries(&query_dir_private);
4950 	if (rc)
4951 		goto err_out;
4952 
4953 	if (!d_info.data_count && d_info.out_buf_len >= 0) {
4954 		if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4955 			rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4956 		} else {
4957 			dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4958 			rsp->hdr.Status = STATUS_NO_MORE_FILES;
4959 		}
4960 		rsp->StructureSize = cpu_to_le16(9);
4961 		rsp->OutputBufferOffset = cpu_to_le16(0);
4962 		rsp->OutputBufferLength = cpu_to_le32(0);
4963 		rsp->Buffer[0] = 0;
4964 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4965 				       offsetof(struct smb2_query_directory_rsp, Buffer)
4966 				       + 1);
4967 		if (rc)
4968 			goto err_out;
4969 	} else {
4970 no_buf_len:
4971 		((FILE_DIRECTORY_INFO *)
4972 		((char *)rsp->Buffer + d_info.last_entry_offset))
4973 		->NextEntryOffset = 0;
4974 		if (d_info.data_count >= d_info.last_entry_off_align)
4975 			d_info.data_count -= d_info.last_entry_off_align;
4976 
4977 		rsp->StructureSize = cpu_to_le16(9);
4978 		rsp->OutputBufferOffset = cpu_to_le16(72);
4979 		rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4980 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4981 				       offsetof(struct smb2_query_directory_rsp, Buffer) +
4982 				       d_info.data_count);
4983 		if (rc)
4984 			goto err_out;
4985 	}
4986 
4987 	mutex_unlock(&dir_fp->readdir_lock);
4988 	kfree(srch_ptr);
4989 	ksmbd_fd_put(work, dir_fp);
4990 	ksmbd_revert_fsids(work);
4991 	return 0;
4992 
4993 err_out:
4994 	pr_err("error while processing smb2 query dir rc = %d\n", rc);
4995 	mutex_unlock(&dir_fp->readdir_lock);
4996 	kfree(srch_ptr);
4997 
4998 err_out2:
4999 	if (rc == -EINVAL)
5000 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5001 	else if (rc == -EACCES)
5002 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
5003 	else if (rc == -ENOENT)
5004 		rsp->hdr.Status = STATUS_NO_SUCH_FILE;
5005 	else if (rc == -EBADF)
5006 		rsp->hdr.Status = STATUS_FILE_CLOSED;
5007 	else if (rc == -ENOMEM)
5008 		rsp->hdr.Status = STATUS_NO_MEMORY;
5009 	else if (rc == -EFAULT)
5010 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5011 	else if (rc == -EIO)
5012 		rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
5013 	if (!rsp->hdr.Status)
5014 		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5015 
5016 	smb2_set_err_rsp(work);
5017 	ksmbd_fd_put(work, dir_fp);
5018 	ksmbd_revert_fsids(work);
5019 	return rc;
5020 }
5021 
5022 /**
5023  * buffer_check_err() - helper function to check buffer errors
5024  * @reqOutputBufferLength:	max buffer length expected in command response
5025  * @rsp:		query info response buffer contains output buffer length
5026  * @rsp_org:		base response buffer pointer in case of chained response
5027  *
5028  * Return:	0 on success, otherwise error
5029  */
5030 static int buffer_check_err(int reqOutputBufferLength,
5031 			    struct smb2_query_info_rsp *rsp,
5032 			    void *rsp_org)
5033 {
5034 	if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
5035 		pr_err("Invalid Buffer Size Requested\n");
5036 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
5037 		*(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
5038 		return -EINVAL;
5039 	}
5040 	return 0;
5041 }
5042 
5043 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
5044 				   void *rsp_org)
5045 {
5046 	struct smb2_file_standard_info *sinfo;
5047 
5048 	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
5049 
5050 	sinfo->AllocationSize = cpu_to_le64(4096);
5051 	sinfo->EndOfFile = cpu_to_le64(0);
5052 	sinfo->NumberOfLinks = cpu_to_le32(1);
5053 	sinfo->DeletePending = 1;
5054 	sinfo->Directory = 0;
5055 	rsp->OutputBufferLength =
5056 		cpu_to_le32(sizeof(struct smb2_file_standard_info));
5057 }
5058 
5059 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
5060 				   void *rsp_org)
5061 {
5062 	struct smb2_file_internal_info *file_info;
5063 
5064 	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
5065 
5066 	/* any unique number */
5067 	file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
5068 	rsp->OutputBufferLength =
5069 		cpu_to_le32(sizeof(struct smb2_file_internal_info));
5070 }
5071 
5072 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
5073 				   struct smb2_query_info_req *req,
5074 				   struct smb2_query_info_rsp *rsp,
5075 				   void *rsp_org)
5076 {
5077 	u64 id;
5078 	int rc;
5079 
5080 	/*
5081 	 * Windows can sometime send query file info request on
5082 	 * pipe without opening it, checking error condition here
5083 	 */
5084 	id = req->VolatileFileId;
5085 
5086 	lockdep_assert_not_held(&sess->rpc_lock);
5087 
5088 	down_read(&sess->rpc_lock);
5089 	if (!ksmbd_session_rpc_method(sess, id)) {
5090 		up_read(&sess->rpc_lock);
5091 		return -ENOENT;
5092 	}
5093 	up_read(&sess->rpc_lock);
5094 
5095 	ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
5096 		    req->FileInfoClass, req->VolatileFileId);
5097 
5098 	switch (req->FileInfoClass) {
5099 	case FILE_STANDARD_INFORMATION:
5100 		get_standard_info_pipe(rsp, rsp_org);
5101 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5102 				      rsp, rsp_org);
5103 		break;
5104 	case FILE_INTERNAL_INFORMATION:
5105 		get_internal_info_pipe(rsp, id, rsp_org);
5106 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5107 				      rsp, rsp_org);
5108 		break;
5109 	default:
5110 		ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
5111 			    req->FileInfoClass);
5112 		rc = -EOPNOTSUPP;
5113 	}
5114 	return rc;
5115 }
5116 
5117 /**
5118  * smb2_get_ea() - handler for smb2 get extended attribute command
5119  * @work:	smb work containing query info command buffer
5120  * @fp:		ksmbd_file pointer
5121  * @req:	get extended attribute request
5122  * @rsp:	response buffer pointer
5123  * @rsp_org:	base response buffer pointer in case of chained response
5124  *
5125  * Return:	0 on success, otherwise error
5126  */
5127 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
5128 		       struct smb2_query_info_req *req,
5129 		       struct smb2_query_info_rsp *rsp, void *rsp_org)
5130 {
5131 	struct smb2_ea_info *eainfo, *prev_eainfo;
5132 	char *name, *ptr, *xattr_list = NULL, *buf;
5133 	int rc, name_len, value_len, xattr_list_len, idx;
5134 	ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
5135 	struct smb2_ea_info_req *ea_req = NULL;
5136 	const struct path *path;
5137 	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
5138 
5139 	if (!(fp->daccess & FILE_READ_EA_LE)) {
5140 		pr_err("Not permitted to read ext attr : 0x%x\n",
5141 		       fp->daccess);
5142 		return -EACCES;
5143 	}
5144 
5145 	path = &fp->filp->f_path;
5146 	/* single EA entry is requested with given user.* name */
5147 	if (req->InputBufferLength) {
5148 		if (le32_to_cpu(req->InputBufferLength) <=
5149 		    sizeof(struct smb2_ea_info_req))
5150 			return -EINVAL;
5151 
5152 		ea_req = (struct smb2_ea_info_req *)((char *)req +
5153 						     le16_to_cpu(req->InputBufferOffset));
5154 
5155 		if (le32_to_cpu(req->InputBufferLength) <
5156 		    offsetof(struct smb2_ea_info_req, name) +
5157 		    ea_req->EaNameLength)
5158 			return -EINVAL;
5159 	} else {
5160 		/* need to send all EAs, if no specific EA is requested*/
5161 		if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
5162 			ksmbd_debug(SMB,
5163 				    "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
5164 				    le32_to_cpu(req->Flags));
5165 	}
5166 
5167 	buf_free_len =
5168 		smb2_calc_max_out_buf_len(work,
5169 				offsetof(struct smb2_query_info_rsp, Buffer),
5170 				le32_to_cpu(req->OutputBufferLength));
5171 	if (buf_free_len < 0)
5172 		return -EINVAL;
5173 
5174 	rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
5175 	if (rc < 0) {
5176 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
5177 		goto out;
5178 	} else if (!rc) { /* there is no EA in the file */
5179 		ksmbd_debug(SMB, "no ea data in the file\n");
5180 		goto done;
5181 	}
5182 	xattr_list_len = rc;
5183 
5184 	ptr = (char *)rsp->Buffer;
5185 	eainfo = (struct smb2_ea_info *)ptr;
5186 	prev_eainfo = eainfo;
5187 	idx = 0;
5188 
5189 	while (idx < xattr_list_len) {
5190 		name = xattr_list + idx;
5191 		name_len = strlen(name);
5192 
5193 		ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
5194 		idx += name_len + 1;
5195 
5196 		/*
5197 		 * CIFS does not support EA other than user.* namespace,
5198 		 * still keep the framework generic, to list other attrs
5199 		 * in future.
5200 		 */
5201 		if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
5202 			continue;
5203 
5204 		if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
5205 			     STREAM_PREFIX_LEN))
5206 			continue;
5207 
5208 		if (req->InputBufferLength &&
5209 		    strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
5210 			    ea_req->EaNameLength))
5211 			continue;
5212 
5213 		if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
5214 			     DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
5215 			continue;
5216 
5217 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
5218 			name_len -= XATTR_USER_PREFIX_LEN;
5219 
5220 		ptr = eainfo->name + name_len + 1;
5221 		buf_free_len -= (offsetof(struct smb2_ea_info, name) +
5222 				name_len + 1);
5223 		/* bailout if xattr can't fit in buf_free_len */
5224 		value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
5225 					       name, &buf);
5226 		if (value_len <= 0) {
5227 			rc = -ENOENT;
5228 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
5229 			goto out;
5230 		}
5231 
5232 		buf_free_len -= value_len;
5233 		if (buf_free_len < 0) {
5234 			kfree(buf);
5235 			break;
5236 		}
5237 
5238 		memcpy(ptr, buf, value_len);
5239 		kfree(buf);
5240 
5241 		ptr += value_len;
5242 		eainfo->Flags = 0;
5243 		eainfo->EaNameLength = name_len;
5244 
5245 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
5246 			memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
5247 			       name_len);
5248 		else
5249 			memcpy(eainfo->name, name, name_len);
5250 
5251 		eainfo->name[name_len] = '\0';
5252 		eainfo->EaValueLength = cpu_to_le16(value_len);
5253 		next_offset = offsetof(struct smb2_ea_info, name) +
5254 			name_len + 1 + value_len;
5255 
5256 		/* align next xattr entry at 4 byte bundary */
5257 		alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
5258 		if (alignment_bytes) {
5259 			if (buf_free_len < alignment_bytes)
5260 				break;
5261 			memset(ptr, '\0', alignment_bytes);
5262 			ptr += alignment_bytes;
5263 			next_offset += alignment_bytes;
5264 			buf_free_len -= alignment_bytes;
5265 		}
5266 		eainfo->NextEntryOffset = cpu_to_le32(next_offset);
5267 		prev_eainfo = eainfo;
5268 		eainfo = (struct smb2_ea_info *)ptr;
5269 		rsp_data_cnt += next_offset;
5270 
5271 		if (req->InputBufferLength) {
5272 			ksmbd_debug(SMB, "single entry requested\n");
5273 			break;
5274 		}
5275 	}
5276 
5277 	/* no more ea entries */
5278 	prev_eainfo->NextEntryOffset = 0;
5279 done:
5280 	rc = 0;
5281 	if (rsp_data_cnt == 0)
5282 		rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
5283 	rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
5284 out:
5285 	kvfree(xattr_list);
5286 	return rc;
5287 }
5288 
5289 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
5290 				 struct ksmbd_file *fp, void *rsp_org)
5291 {
5292 	struct smb2_file_access_info *file_info;
5293 
5294 	file_info = (struct smb2_file_access_info *)rsp->Buffer;
5295 	file_info->AccessFlags = fp->daccess;
5296 	rsp->OutputBufferLength =
5297 		cpu_to_le32(sizeof(struct smb2_file_access_info));
5298 }
5299 
5300 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
5301 			       struct ksmbd_file *fp, void *rsp_org)
5302 {
5303 	struct file_basic_info *basic_info;
5304 	struct kstat stat;
5305 	u64 time;
5306 	int ret;
5307 
5308 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5309 		pr_err("no right to read the attributes : 0x%x\n",
5310 		       fp->daccess);
5311 		return -EACCES;
5312 	}
5313 
5314 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5315 			  AT_STATX_SYNC_AS_STAT);
5316 	if (ret)
5317 		return ret;
5318 
5319 	basic_info = (struct file_basic_info *)rsp->Buffer;
5320 	basic_info->CreationTime = cpu_to_le64(fp->create_time);
5321 	time = ksmbd_UnixTimeToNT(stat.atime);
5322 	basic_info->LastAccessTime = cpu_to_le64(time);
5323 	time = ksmbd_UnixTimeToNT(stat.mtime);
5324 	basic_info->LastWriteTime = cpu_to_le64(time);
5325 	basic_info->ChangeTime = cpu_to_le64(fp->change_time);
5326 	basic_info->Attributes = fp->f_ci->m_fattr;
5327 	basic_info->Pad = 0;
5328 	rsp->OutputBufferLength =
5329 		cpu_to_le32(sizeof(struct file_basic_info));
5330 	return 0;
5331 }
5332 
5333 static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
5334 				  struct ksmbd_file *fp, void *rsp_org)
5335 {
5336 	struct smb2_file_standard_info *sinfo;
5337 	unsigned int delete_pending;
5338 	struct kstat stat;
5339 	int ret;
5340 
5341 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5342 			  AT_STATX_SYNC_AS_STAT);
5343 	if (ret)
5344 		return ret;
5345 
5346 	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
5347 	delete_pending = ksmbd_inode_pending_delete(fp);
5348 
5349 	if (ksmbd_stream_fd(fp) == false) {
5350 		sinfo->AllocationSize = cpu_to_le64(fp->allocation_size);
5351 		sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5352 	} else {
5353 		sinfo->AllocationSize = cpu_to_le64(fp->stream.size);
5354 		sinfo->EndOfFile = cpu_to_le64(fp->stream.size);
5355 	}
5356 	sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
5357 	sinfo->DeletePending = delete_pending;
5358 	sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
5359 	rsp->OutputBufferLength =
5360 		cpu_to_le32(sizeof(struct smb2_file_standard_info));
5361 
5362 	return 0;
5363 }
5364 
5365 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
5366 				    void *rsp_org)
5367 {
5368 	struct smb2_file_alignment_info *file_info;
5369 
5370 	file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
5371 	file_info->AlignmentRequirement = 0;
5372 	rsp->OutputBufferLength =
5373 		cpu_to_le32(sizeof(struct smb2_file_alignment_info));
5374 }
5375 
5376 static int get_file_all_info(struct ksmbd_work *work,
5377 			     struct smb2_query_info_rsp *rsp,
5378 			     struct ksmbd_file *fp,
5379 			     void *rsp_org)
5380 {
5381 	struct ksmbd_conn *conn = work->conn;
5382 	struct smb2_file_all_info *file_info;
5383 	unsigned int delete_pending;
5384 	struct kstat stat;
5385 	int conv_len;
5386 	char *filename;
5387 	u64 time;
5388 	int ret, buf_free_len, filename_len;
5389 	struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
5390 
5391 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5392 		ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
5393 			    fp->daccess);
5394 		return -EACCES;
5395 	}
5396 
5397 	filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
5398 	if (IS_ERR(filename))
5399 		return PTR_ERR(filename);
5400 
5401 	filename_len = strlen(filename);
5402 	buf_free_len = smb2_calc_max_out_buf_len(work,
5403 			offsetof(struct smb2_query_info_rsp, Buffer) +
5404 			offsetof(struct smb2_file_all_info, FileName),
5405 			le32_to_cpu(req->OutputBufferLength));
5406 	if (buf_free_len < (filename_len + 1) * 2) {
5407 		kfree(filename);
5408 		return -EINVAL;
5409 	}
5410 
5411 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5412 			  AT_STATX_SYNC_AS_STAT);
5413 	if (ret) {
5414 		kfree(filename);
5415 		return ret;
5416 	}
5417 
5418 	ksmbd_debug(SMB, "filename = %s\n", filename);
5419 	delete_pending = ksmbd_inode_pending_delete(fp);
5420 	file_info = (struct smb2_file_all_info *)rsp->Buffer;
5421 
5422 	file_info->CreationTime = cpu_to_le64(fp->create_time);
5423 	time = ksmbd_UnixTimeToNT(stat.atime);
5424 	file_info->LastAccessTime = cpu_to_le64(time);
5425 	time = ksmbd_UnixTimeToNT(stat.mtime);
5426 	file_info->LastWriteTime = cpu_to_le64(time);
5427 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
5428 	file_info->Attributes = fp->f_ci->m_fattr;
5429 	file_info->Pad1 = 0;
5430 	if (ksmbd_stream_fd(fp) == false) {
5431 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
5432 		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5433 	} else {
5434 		file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5435 		file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5436 	}
5437 	file_info->NumberOfLinks =
5438 			cpu_to_le32(get_nlink(&stat) - delete_pending);
5439 	file_info->DeletePending = delete_pending;
5440 	file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
5441 	file_info->Pad2 = 0;
5442 	file_info->IndexNumber = cpu_to_le64(stat.ino);
5443 	file_info->EASize = 0;
5444 	file_info->AccessFlags = fp->daccess;
5445 	if (ksmbd_stream_fd(fp) == false)
5446 		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5447 	else
5448 		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
5449 	file_info->Mode = fp->coption;
5450 	file_info->AlignmentRequirement = 0;
5451 	conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
5452 				     min(filename_len, PATH_MAX),
5453 				     conn->local_nls, 0);
5454 	conv_len *= 2;
5455 	file_info->FileNameLength = cpu_to_le32(conv_len);
5456 	rsp->OutputBufferLength =
5457 		cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
5458 	kfree(filename);
5459 	return 0;
5460 }
5461 
5462 static void get_file_alternate_info(struct ksmbd_work *work,
5463 				    struct smb2_query_info_rsp *rsp,
5464 				    struct ksmbd_file *fp,
5465 				    void *rsp_org)
5466 {
5467 	struct ksmbd_conn *conn = work->conn;
5468 	struct smb2_file_alt_name_info *file_info;
5469 	struct dentry *dentry = fp->filp->f_path.dentry;
5470 	int conv_len;
5471 
5472 	spin_lock(&dentry->d_lock);
5473 	file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
5474 	conv_len = ksmbd_extract_shortname(conn,
5475 					   dentry->d_name.name,
5476 					   file_info->FileName);
5477 	spin_unlock(&dentry->d_lock);
5478 	file_info->FileNameLength = cpu_to_le32(conv_len);
5479 	rsp->OutputBufferLength =
5480 		cpu_to_le32(struct_size(file_info, FileName, conv_len));
5481 }
5482 
5483 static int get_file_stream_info(struct ksmbd_work *work,
5484 				struct smb2_query_info_rsp *rsp,
5485 				struct ksmbd_file *fp,
5486 				void *rsp_org)
5487 {
5488 	struct ksmbd_conn *conn = work->conn;
5489 	struct smb2_file_stream_info *file_info;
5490 	char *stream_name, *xattr_list = NULL, *stream_buf;
5491 	struct kstat stat;
5492 	const struct path *path = &fp->filp->f_path;
5493 	ssize_t xattr_list_len;
5494 	int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
5495 	int buf_free_len;
5496 	struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
5497 	int ret;
5498 
5499 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5500 			  AT_STATX_SYNC_AS_STAT);
5501 	if (ret)
5502 		return ret;
5503 
5504 	file_info = (struct smb2_file_stream_info *)rsp->Buffer;
5505 
5506 	buf_free_len =
5507 		smb2_calc_max_out_buf_len(work,
5508 				offsetof(struct smb2_query_info_rsp, Buffer),
5509 				le32_to_cpu(req->OutputBufferLength));
5510 	if (buf_free_len < 0)
5511 		goto out;
5512 
5513 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
5514 	if (xattr_list_len < 0) {
5515 		goto out;
5516 	} else if (!xattr_list_len) {
5517 		ksmbd_debug(SMB, "empty xattr in the file\n");
5518 		goto out;
5519 	}
5520 
5521 	while (idx < xattr_list_len) {
5522 		stream_name = xattr_list + idx;
5523 		streamlen = strlen(stream_name);
5524 		idx += streamlen + 1;
5525 
5526 		ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
5527 
5528 		if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
5529 			    STREAM_PREFIX, STREAM_PREFIX_LEN))
5530 			continue;
5531 
5532 		stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
5533 				STREAM_PREFIX_LEN);
5534 		streamlen = stream_name_len;
5535 
5536 		/* plus : size */
5537 		streamlen += 1;
5538 		stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP);
5539 		if (!stream_buf)
5540 			break;
5541 
5542 		streamlen = snprintf(stream_buf, streamlen + 1,
5543 				     ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
5544 
5545 		next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
5546 		if (next > buf_free_len) {
5547 			kfree(stream_buf);
5548 			break;
5549 		}
5550 
5551 		file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
5552 		streamlen  = smbConvertToUTF16((__le16 *)file_info->StreamName,
5553 					       stream_buf, streamlen,
5554 					       conn->local_nls, 0);
5555 		streamlen *= 2;
5556 		kfree(stream_buf);
5557 		file_info->StreamNameLength = cpu_to_le32(streamlen);
5558 		file_info->StreamSize = cpu_to_le64(stream_name_len);
5559 		file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
5560 
5561 		nbytes += next;
5562 		buf_free_len -= next;
5563 		file_info->NextEntryOffset = cpu_to_le32(next);
5564 	}
5565 
5566 out:
5567 	if (!S_ISDIR(stat.mode) &&
5568 	    buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
5569 		file_info = (struct smb2_file_stream_info *)
5570 			&rsp->Buffer[nbytes];
5571 		streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
5572 					      "::$DATA", 7, conn->local_nls, 0);
5573 		streamlen *= 2;
5574 		file_info->StreamNameLength = cpu_to_le32(streamlen);
5575 		file_info->StreamSize = cpu_to_le64(stat.size);
5576 		file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
5577 		nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
5578 	}
5579 
5580 	/* last entry offset should be 0 */
5581 	file_info->NextEntryOffset = 0;
5582 	kvfree(xattr_list);
5583 
5584 	rsp->OutputBufferLength = cpu_to_le32(nbytes);
5585 
5586 	return 0;
5587 }
5588 
5589 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
5590 				  struct ksmbd_file *fp, void *rsp_org)
5591 {
5592 	struct smb2_file_internal_info *file_info;
5593 	struct kstat stat;
5594 	int ret;
5595 
5596 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5597 			  AT_STATX_SYNC_AS_STAT);
5598 	if (ret)
5599 		return ret;
5600 
5601 	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
5602 	file_info->IndexNumber = cpu_to_le64(stat.ino);
5603 	rsp->OutputBufferLength =
5604 		cpu_to_le32(sizeof(struct smb2_file_internal_info));
5605 
5606 	return 0;
5607 }
5608 
5609 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
5610 				      struct ksmbd_file *fp, void *rsp_org)
5611 {
5612 	struct smb2_file_network_open_info *file_info;
5613 	struct kstat stat;
5614 	u64 time;
5615 	int ret;
5616 
5617 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5618 		pr_err("no right to read the attributes : 0x%x\n",
5619 		       fp->daccess);
5620 		return -EACCES;
5621 	}
5622 
5623 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5624 			  AT_STATX_SYNC_AS_STAT);
5625 	if (ret)
5626 		return ret;
5627 
5628 	file_info = (struct smb2_file_network_open_info *)rsp->Buffer;
5629 
5630 	file_info->CreationTime = cpu_to_le64(fp->create_time);
5631 	time = ksmbd_UnixTimeToNT(stat.atime);
5632 	file_info->LastAccessTime = cpu_to_le64(time);
5633 	time = ksmbd_UnixTimeToNT(stat.mtime);
5634 	file_info->LastWriteTime = cpu_to_le64(time);
5635 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
5636 	file_info->Attributes = fp->f_ci->m_fattr;
5637 	if (ksmbd_stream_fd(fp) == false) {
5638 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
5639 		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5640 	} else {
5641 		file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5642 		file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5643 	}
5644 	file_info->Reserved = cpu_to_le32(0);
5645 	rsp->OutputBufferLength =
5646 		cpu_to_le32(sizeof(struct smb2_file_network_open_info));
5647 	return 0;
5648 }
5649 
5650 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
5651 {
5652 	struct smb2_file_ea_info *file_info;
5653 
5654 	file_info = (struct smb2_file_ea_info *)rsp->Buffer;
5655 	file_info->EASize = 0;
5656 	rsp->OutputBufferLength =
5657 		cpu_to_le32(sizeof(struct smb2_file_ea_info));
5658 }
5659 
5660 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
5661 				   struct ksmbd_file *fp, void *rsp_org)
5662 {
5663 	struct smb2_file_pos_info *file_info;
5664 
5665 	file_info = (struct smb2_file_pos_info *)rsp->Buffer;
5666 	if (ksmbd_stream_fd(fp) == false)
5667 		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5668 	else
5669 		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
5670 
5671 	rsp->OutputBufferLength =
5672 		cpu_to_le32(sizeof(struct smb2_file_pos_info));
5673 }
5674 
5675 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
5676 			       struct ksmbd_file *fp, void *rsp_org)
5677 {
5678 	struct smb2_file_mode_info *file_info;
5679 
5680 	file_info = (struct smb2_file_mode_info *)rsp->Buffer;
5681 	file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
5682 	rsp->OutputBufferLength =
5683 		cpu_to_le32(sizeof(struct smb2_file_mode_info));
5684 }
5685 
5686 static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
5687 				     struct ksmbd_file *fp, void *rsp_org)
5688 {
5689 	struct smb2_file_comp_info *file_info;
5690 	struct kstat stat;
5691 	u16 fmt;
5692 	int ret;
5693 
5694 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5695 			  AT_STATX_SYNC_AS_STAT);
5696 	if (ret)
5697 		return ret;
5698 
5699 	ret = ksmbd_vfs_get_compression(fp, &fmt);
5700 	if (ret)
5701 		return ret;
5702 
5703 	file_info = (struct smb2_file_comp_info *)rsp->Buffer;
5704 	file_info->CompressedFileSize = cpu_to_le64(min_t(u64, stat.blocks << 9, stat.size));
5705 	file_info->CompressionFormat = cpu_to_le16(fmt);
5706 	file_info->CompressionUnitShift = 0;
5707 	file_info->ChunkShift = 0;
5708 	file_info->ClusterShift = 0;
5709 	memset(&file_info->Reserved[0], 0, 3);
5710 
5711 	rsp->OutputBufferLength =
5712 		cpu_to_le32(sizeof(struct smb2_file_comp_info));
5713 
5714 	return 0;
5715 }
5716 
5717 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
5718 				       struct ksmbd_file *fp, void *rsp_org)
5719 {
5720 	struct smb2_file_attr_tag_info *file_info;
5721 
5722 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5723 		pr_err("no right to read the attributes : 0x%x\n",
5724 		       fp->daccess);
5725 		return -EACCES;
5726 	}
5727 
5728 	file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
5729 	file_info->FileAttributes = fp->f_ci->m_fattr;
5730 	file_info->ReparseTag = 0;
5731 	rsp->OutputBufferLength =
5732 		cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
5733 	return 0;
5734 }
5735 
5736 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
5737 				struct ksmbd_file *fp, void *rsp_org)
5738 {
5739 	struct smb311_posix_qinfo *file_info;
5740 	struct inode *inode = file_inode(fp->filp);
5741 	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
5742 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
5743 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
5744 	struct kstat stat;
5745 	u64 time;
5746 	int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
5747 	int ret;
5748 
5749 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5750 		pr_err("no right to read the attributes : 0x%x\n",
5751 		       fp->daccess);
5752 		return -EACCES;
5753 	}
5754 
5755 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5756 			  AT_STATX_SYNC_AS_STAT);
5757 	if (ret)
5758 		return ret;
5759 
5760 	file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
5761 	file_info->CreationTime = cpu_to_le64(fp->create_time);
5762 	time = ksmbd_UnixTimeToNT(stat.atime);
5763 	file_info->LastAccessTime = cpu_to_le64(time);
5764 	time = ksmbd_UnixTimeToNT(stat.mtime);
5765 	file_info->LastWriteTime = cpu_to_le64(time);
5766 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
5767 	file_info->DosAttributes = fp->f_ci->m_fattr;
5768 	file_info->Inode = cpu_to_le64(stat.ino);
5769 	if (ksmbd_stream_fd(fp) == false) {
5770 		file_info->EndOfFile = cpu_to_le64(stat.size);
5771 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
5772 	} else {
5773 		file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5774 		file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5775 	}
5776 	file_info->HardLinks = cpu_to_le32(stat.nlink);
5777 	file_info->Mode = cpu_to_le32(stat.mode & 0777);
5778 	switch (stat.mode & S_IFMT) {
5779 	case S_IFDIR:
5780 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
5781 		break;
5782 	case S_IFLNK:
5783 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
5784 		break;
5785 	case S_IFCHR:
5786 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
5787 		break;
5788 	case S_IFBLK:
5789 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
5790 		break;
5791 	case S_IFIFO:
5792 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
5793 		break;
5794 	case S_IFSOCK:
5795 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
5796 	}
5797 
5798 	file_info->DeviceId = cpu_to_le32(stat.rdev);
5799 
5800 	/*
5801 	 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
5802 	 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
5803 	 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
5804 	 */
5805 	id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
5806 		  SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
5807 	id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
5808 		  SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
5809 
5810 	rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
5811 
5812 	return 0;
5813 }
5814 
5815 static int smb2_get_info_file(struct ksmbd_work *work,
5816 			      struct smb2_query_info_req *req,
5817 			      struct smb2_query_info_rsp *rsp)
5818 {
5819 	struct ksmbd_file *fp;
5820 	int fileinfoclass = 0;
5821 	int rc = 0;
5822 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5823 
5824 	if (test_share_config_flag(work->tcon->share_conf,
5825 				   KSMBD_SHARE_FLAG_PIPE)) {
5826 		/* smb2 info file called for pipe */
5827 		rc = smb2_get_info_file_pipe(work->sess, req, rsp,
5828 					       work->response_buf);
5829 		goto iov_pin_out;
5830 	}
5831 
5832 	if (work->next_smb2_rcv_hdr_off) {
5833 		if (!has_file_id(req->VolatileFileId)) {
5834 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5835 				    work->compound_fid);
5836 			id = work->compound_fid;
5837 			pid = work->compound_pfid;
5838 		}
5839 	}
5840 
5841 	if (!has_file_id(id)) {
5842 		id = req->VolatileFileId;
5843 		pid = req->PersistentFileId;
5844 	}
5845 
5846 	fp = ksmbd_lookup_fd_slow(work, id, pid);
5847 	if (!fp)
5848 		return -ENOENT;
5849 
5850 	fileinfoclass = req->FileInfoClass;
5851 
5852 	switch (fileinfoclass) {
5853 	case FILE_ACCESS_INFORMATION:
5854 		get_file_access_info(rsp, fp, work->response_buf);
5855 		break;
5856 
5857 	case FILE_BASIC_INFORMATION:
5858 		rc = get_file_basic_info(rsp, fp, work->response_buf);
5859 		break;
5860 
5861 	case FILE_STANDARD_INFORMATION:
5862 		rc = get_file_standard_info(rsp, fp, work->response_buf);
5863 		break;
5864 
5865 	case FILE_ALIGNMENT_INFORMATION:
5866 		get_file_alignment_info(rsp, work->response_buf);
5867 		break;
5868 
5869 	case FILE_ALL_INFORMATION:
5870 		rc = get_file_all_info(work, rsp, fp, work->response_buf);
5871 		break;
5872 
5873 	case FILE_ALTERNATE_NAME_INFORMATION:
5874 		get_file_alternate_info(work, rsp, fp, work->response_buf);
5875 		break;
5876 
5877 	case FILE_STREAM_INFORMATION:
5878 		rc = get_file_stream_info(work, rsp, fp, work->response_buf);
5879 		break;
5880 
5881 	case FILE_INTERNAL_INFORMATION:
5882 		rc = get_file_internal_info(rsp, fp, work->response_buf);
5883 		break;
5884 
5885 	case FILE_NETWORK_OPEN_INFORMATION:
5886 		rc = get_file_network_open_info(rsp, fp, work->response_buf);
5887 		break;
5888 
5889 	case FILE_EA_INFORMATION:
5890 		get_file_ea_info(rsp, work->response_buf);
5891 		break;
5892 
5893 	case FILE_FULL_EA_INFORMATION:
5894 		rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
5895 		break;
5896 
5897 	case FILE_POSITION_INFORMATION:
5898 		get_file_position_info(rsp, fp, work->response_buf);
5899 		break;
5900 
5901 	case FILE_MODE_INFORMATION:
5902 		get_file_mode_info(rsp, fp, work->response_buf);
5903 		break;
5904 
5905 	case FILE_COMPRESSION_INFORMATION:
5906 		rc = get_file_compression_info(rsp, fp, work->response_buf);
5907 		break;
5908 
5909 	case FILE_ATTRIBUTE_TAG_INFORMATION:
5910 		rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
5911 		break;
5912 	case SMB_FIND_FILE_POSIX_INFO:
5913 		if (!work->tcon->posix_extensions) {
5914 			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5915 			rc = -EOPNOTSUPP;
5916 		} else {
5917 			rc = find_file_posix_info(rsp, fp, work->response_buf);
5918 		}
5919 		break;
5920 	default:
5921 		ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
5922 			    fileinfoclass);
5923 		rc = -EOPNOTSUPP;
5924 	}
5925 	if (!rc)
5926 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5927 				      rsp, work->response_buf);
5928 	ksmbd_fd_put(work, fp);
5929 
5930 iov_pin_out:
5931 	if (!rc)
5932 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5933 				offsetof(struct smb2_query_info_rsp, Buffer) +
5934 				le32_to_cpu(rsp->OutputBufferLength));
5935 	return rc;
5936 }
5937 
5938 static int smb2_get_info_filesystem(struct ksmbd_work *work,
5939 				    struct smb2_query_info_req *req,
5940 				    struct smb2_query_info_rsp *rsp)
5941 {
5942 	struct ksmbd_conn *conn = work->conn;
5943 	struct ksmbd_share_config *share = work->tcon->share_conf;
5944 	int fsinfoclass = 0;
5945 	struct kstatfs stfs;
5946 	struct path path;
5947 	int rc = 0, len;
5948 
5949 	if (!share->path)
5950 		return -EIO;
5951 
5952 	rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
5953 	if (rc) {
5954 		pr_err("cannot create vfs path\n");
5955 		return -EIO;
5956 	}
5957 
5958 	rc = vfs_statfs(&path, &stfs);
5959 	if (rc) {
5960 		pr_err("cannot do stat of path %s\n", share->path);
5961 		path_put(&path);
5962 		return -EIO;
5963 	}
5964 
5965 	fsinfoclass = req->FileInfoClass;
5966 
5967 	switch (fsinfoclass) {
5968 	case FS_DEVICE_INFORMATION:
5969 	{
5970 		FILE_SYSTEM_DEVICE_INFO *info;
5971 
5972 		info = (FILE_SYSTEM_DEVICE_INFO *)rsp->Buffer;
5973 
5974 		info->DeviceType = cpu_to_le32(FILE_DEVICE_DISK);
5975 		info->DeviceCharacteristics =
5976 			cpu_to_le32(FILE_DEVICE_IS_MOUNTED);
5977 		if (!test_tree_conn_flag(work->tcon,
5978 					 KSMBD_TREE_CONN_FLAG_WRITABLE))
5979 			info->DeviceCharacteristics |=
5980 				cpu_to_le32(FILE_READ_ONLY_DEVICE);
5981 		rsp->OutputBufferLength = cpu_to_le32(8);
5982 		break;
5983 	}
5984 	case FS_ATTRIBUTE_INFORMATION:
5985 	{
5986 		FILE_SYSTEM_ATTRIBUTE_INFO *info;
5987 		struct file_kattr fa = {};
5988 		size_t sz;
5989 		u32 attrs;
5990 		int err;
5991 
5992 		info = (FILE_SYSTEM_ATTRIBUTE_INFO *)rsp->Buffer;
5993 		attrs = FILE_SUPPORTS_OBJECT_IDS |
5994 			FILE_PERSISTENT_ACLS |
5995 			FILE_UNICODE_ON_DISK |
5996 			FILE_SUPPORTS_BLOCK_REFCOUNTING;
5997 
5998 		err = vfs_fileattr_get(path.dentry, &fa);
5999 		/*
6000 		 * -EINVAL, -EOPNOTSUPP: ntfs-3g and other FUSE
6001 		 * filesystems that lack FS_IOC_FSGETXATTR support.
6002 		 */
6003 		if (err && err != -ENOIOCTLCMD && err != -ENOTTY &&
6004 		    err != -EINVAL && err != -EOPNOTSUPP) {
6005 			path_put(&path);
6006 			return err;
6007 		}
6008 		if (!(fa.fsx_xflags & FS_XFLAG_CASEFOLD))
6009 			attrs |= FILE_CASE_SENSITIVE_SEARCH;
6010 		if (!(fa.fsx_xflags & FS_XFLAG_CASENONPRESERVING))
6011 			attrs |= FILE_CASE_PRESERVED_NAMES;
6012 
6013 		info->Attributes = cpu_to_le32(attrs);
6014 		info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
6015 
6016 		if (test_share_config_flag(work->tcon->share_conf,
6017 		    KSMBD_SHARE_FLAG_STREAMS))
6018 			info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
6019 
6020 		info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
6021 		/*
6022 		 * some application(potableapp) can not run on ksmbd share
6023 		 * because only NTFS handle security setting on windows.
6024 		 * So Although local fs(EXT4 or F2fs, etc) is not NTFS,
6025 		 * ksmbd should show share as NTFS. Later, If needed, we can add
6026 		 * fs type(s) parameter to change fs type user wanted.
6027 		 */
6028 		len = smbConvertToUTF16((__le16 *)info->FileSystemName,
6029 					"NTFS", PATH_MAX, conn->local_nls, 0);
6030 		len = len * 2;
6031 		info->FileSystemNameLen = cpu_to_le32(len);
6032 		sz = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + len;
6033 		rsp->OutputBufferLength = cpu_to_le32(sz);
6034 		break;
6035 	}
6036 	case FS_VOLUME_INFORMATION:
6037 	{
6038 		struct filesystem_vol_info *info;
6039 		size_t sz;
6040 		unsigned int serial_crc = 0;
6041 
6042 		info = (struct filesystem_vol_info *)(rsp->Buffer);
6043 		info->VolumeCreationTime = 0;
6044 		serial_crc = crc32_le(serial_crc, share->name,
6045 				      strlen(share->name));
6046 		serial_crc = crc32_le(serial_crc, share->path,
6047 				      strlen(share->path));
6048 		serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
6049 				      strlen(ksmbd_netbios_name()));
6050 		/* Taking dummy value of serial number*/
6051 		info->VolumeSerialNumber = cpu_to_le32(serial_crc);
6052 		len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
6053 					share->name, PATH_MAX,
6054 					conn->local_nls, 0);
6055 		len = len * 2;
6056 		info->VolumeLabelLength = cpu_to_le32(len);
6057 		info->Reserved = 0;
6058 		info->SupportsObjects = 0;
6059 		sz = sizeof(struct filesystem_vol_info) + len;
6060 		rsp->OutputBufferLength = cpu_to_le32(sz);
6061 		break;
6062 	}
6063 	case FS_SIZE_INFORMATION:
6064 	{
6065 		FILE_SYSTEM_SIZE_INFO *info;
6066 
6067 		info = (FILE_SYSTEM_SIZE_INFO *)(rsp->Buffer);
6068 		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
6069 		info->AvailableAllocationUnits = cpu_to_le64(stfs.f_bfree);
6070 		info->SectorsPerAllocationUnit = cpu_to_le32(1);
6071 		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
6072 		rsp->OutputBufferLength = cpu_to_le32(24);
6073 		break;
6074 	}
6075 	case FS_FULL_SIZE_INFORMATION:
6076 	{
6077 		struct smb2_fs_full_size_info *info;
6078 
6079 		info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
6080 		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
6081 		info->CallerAvailableAllocationUnits =
6082 					cpu_to_le64(stfs.f_bavail);
6083 		info->ActualAvailableAllocationUnits =
6084 					cpu_to_le64(stfs.f_bfree);
6085 		info->SectorsPerAllocationUnit = cpu_to_le32(1);
6086 		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
6087 		rsp->OutputBufferLength = cpu_to_le32(32);
6088 		break;
6089 	}
6090 	case FS_OBJECT_ID_INFORMATION:
6091 	{
6092 		struct object_id_info *info;
6093 
6094 		info = (struct object_id_info *)(rsp->Buffer);
6095 
6096 		if (path.mnt->mnt_sb->s_uuid_len == 16)
6097 			memcpy(info->objid, path.mnt->mnt_sb->s_uuid.b,
6098 					path.mnt->mnt_sb->s_uuid_len);
6099 		else
6100 			memcpy(info->objid, &stfs.f_fsid, sizeof(stfs.f_fsid));
6101 
6102 		info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
6103 		info->extended_info.version = cpu_to_le32(1);
6104 		info->extended_info.release = cpu_to_le32(1);
6105 		info->extended_info.rel_date = 0;
6106 		memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
6107 		rsp->OutputBufferLength = cpu_to_le32(64);
6108 		break;
6109 	}
6110 	case FS_SECTOR_SIZE_INFORMATION:
6111 	{
6112 		struct smb3_fs_ss_info *info;
6113 		unsigned int sector_size =
6114 			min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
6115 
6116 		info = (struct smb3_fs_ss_info *)(rsp->Buffer);
6117 
6118 		info->LogicalBytesPerSector = cpu_to_le32(sector_size);
6119 		info->PhysicalBytesPerSectorForAtomicity =
6120 				cpu_to_le32(sector_size);
6121 		info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
6122 		info->FSEffPhysicalBytesPerSectorForAtomicity =
6123 				cpu_to_le32(sector_size);
6124 		info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
6125 				    SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
6126 		info->ByteOffsetForSectorAlignment = 0;
6127 		info->ByteOffsetForPartitionAlignment = 0;
6128 		rsp->OutputBufferLength = cpu_to_le32(28);
6129 		break;
6130 	}
6131 	case FS_CONTROL_INFORMATION:
6132 	{
6133 		/*
6134 		 * TODO : The current implementation is based on
6135 		 * test result with win7(NTFS) server. It's need to
6136 		 * modify this to get valid Quota values
6137 		 * from Linux kernel
6138 		 */
6139 		struct smb2_fs_control_info *info;
6140 
6141 		info = (struct smb2_fs_control_info *)(rsp->Buffer);
6142 		info->FreeSpaceStartFiltering = 0;
6143 		info->FreeSpaceThreshold = 0;
6144 		info->FreeSpaceStopFiltering = 0;
6145 		info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
6146 		info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
6147 		info->Padding = 0;
6148 		rsp->OutputBufferLength = cpu_to_le32(48);
6149 		break;
6150 	}
6151 	case FS_POSIX_INFORMATION:
6152 	{
6153 		FILE_SYSTEM_POSIX_INFO *info;
6154 
6155 		if (!work->tcon->posix_extensions) {
6156 			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
6157 			path_put(&path);
6158 			return -EOPNOTSUPP;
6159 		} else {
6160 			info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
6161 			info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
6162 			info->BlockSize = cpu_to_le32(stfs.f_bsize);
6163 			info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
6164 			info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
6165 			info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
6166 			info->TotalFileNodes = cpu_to_le64(stfs.f_files);
6167 			info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
6168 			rsp->OutputBufferLength = cpu_to_le32(56);
6169 		}
6170 		break;
6171 	}
6172 	default:
6173 		path_put(&path);
6174 		return -EOPNOTSUPP;
6175 	}
6176 	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
6177 			      rsp, work->response_buf);
6178 	path_put(&path);
6179 
6180 	if (!rc)
6181 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6182 				offsetof(struct smb2_query_info_rsp, Buffer) +
6183 				le32_to_cpu(rsp->OutputBufferLength));
6184 	return rc;
6185 }
6186 
6187 static int smb2_get_info_sec(struct ksmbd_work *work,
6188 			     struct smb2_query_info_req *req,
6189 			     struct smb2_query_info_rsp *rsp)
6190 {
6191 	struct ksmbd_file *fp;
6192 	struct mnt_idmap *idmap;
6193 	struct smb_ntsd *pntsd = NULL, *ppntsd = NULL;
6194 	struct smb_fattr fattr = {{0}};
6195 	struct inode *inode;
6196 	__u32 secdesclen = 0;
6197 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6198 	int addition_info = le32_to_cpu(req->AdditionalInformation);
6199 	int rc = 0, ppntsd_size = 0, max_len;
6200 	size_t scratch_len = 0;
6201 
6202 	if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
6203 			      PROTECTED_DACL_SECINFO |
6204 			      UNPROTECTED_DACL_SECINFO)) {
6205 		ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
6206 		       addition_info);
6207 
6208 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6209 		return -EINVAL;
6210 	}
6211 
6212 	if (work->next_smb2_rcv_hdr_off) {
6213 		if (!has_file_id(req->VolatileFileId)) {
6214 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6215 				    work->compound_fid);
6216 			id = work->compound_fid;
6217 			pid = work->compound_pfid;
6218 		}
6219 	}
6220 
6221 	if (!has_file_id(id)) {
6222 		id = req->VolatileFileId;
6223 		pid = req->PersistentFileId;
6224 	}
6225 
6226 	fp = ksmbd_lookup_fd_slow(work, id, pid);
6227 	if (!fp)
6228 		return -ENOENT;
6229 
6230 	idmap = file_mnt_idmap(fp->filp);
6231 	inode = file_inode(fp->filp);
6232 	ksmbd_acls_fattr(&fattr, idmap, inode);
6233 
6234 	if (test_share_config_flag(work->tcon->share_conf,
6235 				   KSMBD_SHARE_FLAG_ACL_XATTR))
6236 		ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
6237 						     fp->filp->f_path.dentry,
6238 						     &ppntsd);
6239 
6240 	/* Check if sd buffer size exceeds response buffer size */
6241 	max_len = smb2_calc_max_out_buf_len(work,
6242 			offsetof(struct smb2_query_info_rsp, Buffer),
6243 			le32_to_cpu(req->OutputBufferLength));
6244 	if (max_len < 0) {
6245 		rc = -EINVAL;
6246 		goto release_acl;
6247 	}
6248 
6249 	scratch_len = smb_acl_sec_desc_scratch_len(&fattr, ppntsd,
6250 			ppntsd_size, addition_info);
6251 	if (!scratch_len || scratch_len == SIZE_MAX) {
6252 		rc = -EFBIG;
6253 		goto release_acl;
6254 	}
6255 
6256 	pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
6257 	if (!pntsd) {
6258 		rc = -ENOMEM;
6259 		goto release_acl;
6260 	}
6261 
6262 	rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
6263 			addition_info, &secdesclen, &fattr);
6264 
6265 release_acl:
6266 	posix_acl_release(fattr.cf_acls);
6267 	posix_acl_release(fattr.cf_dacls);
6268 	kfree(ppntsd);
6269 	ksmbd_fd_put(work, fp);
6270 
6271 	if (!rc && ALIGN(secdesclen, 8) > scratch_len)
6272 		rc = -EFBIG;
6273 	if (rc)
6274 		goto err_out;
6275 
6276 	rsp->OutputBufferLength = cpu_to_le32(secdesclen);
6277 	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
6278 			      rsp, work->response_buf);
6279 	if (rc)
6280 		goto err_out;
6281 
6282 	rc = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6283 			offsetof(struct smb2_query_info_rsp, Buffer),
6284 			pntsd, secdesclen);
6285 err_out:
6286 	if (rc) {
6287 		rsp->OutputBufferLength = 0;
6288 		kvfree(pntsd);
6289 	}
6290 
6291 	return rc;
6292 }
6293 
6294 /**
6295  * smb2_query_info() - handler for smb2 query info command
6296  * @work:	smb work containing query info request buffer
6297  *
6298  * Return:	0 on success, otherwise error
6299  */
6300 int smb2_query_info(struct ksmbd_work *work)
6301 {
6302 	struct smb2_query_info_req *req;
6303 	struct smb2_query_info_rsp *rsp;
6304 	int rc = 0;
6305 
6306 	ksmbd_debug(SMB, "Received request smb2 query info request\n");
6307 
6308 	WORK_BUFFERS(work, req, rsp);
6309 
6310 	if (smb2_compound_has_failed(work, &rsp->hdr))
6311 		return -EACCES;
6312 
6313 	if (ksmbd_override_fsids(work)) {
6314 		rc = -ENOMEM;
6315 		goto err_out;
6316 	}
6317 
6318 	rsp->StructureSize = cpu_to_le16(9);
6319 	rsp->OutputBufferOffset = cpu_to_le16(72);
6320 
6321 	switch (req->InfoType) {
6322 	case SMB2_O_INFO_FILE:
6323 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6324 		rc = smb2_get_info_file(work, req, rsp);
6325 		break;
6326 	case SMB2_O_INFO_FILESYSTEM:
6327 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
6328 		rc = smb2_get_info_filesystem(work, req, rsp);
6329 		break;
6330 	case SMB2_O_INFO_SECURITY:
6331 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6332 		rc = smb2_get_info_sec(work, req, rsp);
6333 		break;
6334 	default:
6335 		ksmbd_debug(SMB, "InfoType %d not supported yet\n",
6336 			    req->InfoType);
6337 		rc = -EOPNOTSUPP;
6338 	}
6339 	ksmbd_revert_fsids(work);
6340 
6341 err_out:
6342 	if (rc < 0) {
6343 		if (rc == -EACCES)
6344 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
6345 		else if (rc == -ENOENT)
6346 			rsp->hdr.Status = STATUS_FILE_CLOSED;
6347 		else if (rc == -EIO)
6348 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6349 		else if (rc == -ENOMEM)
6350 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
6351 		else if (rc == -EINVAL && rsp->hdr.Status == 0)
6352 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6353 		else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
6354 			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6355 		smb2_set_err_rsp(work);
6356 
6357 		ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
6358 			    rc);
6359 		return rc;
6360 	}
6361 	return 0;
6362 }
6363 
6364 /**
6365  * smb2_close_pipe() - handler for closing IPC pipe
6366  * @work:	smb work containing close request buffer
6367  *
6368  * Return:	0
6369  */
6370 static noinline int smb2_close_pipe(struct ksmbd_work *work)
6371 {
6372 	u64 id;
6373 	struct smb2_close_req *req;
6374 	struct smb2_close_rsp *rsp;
6375 
6376 	WORK_BUFFERS(work, req, rsp);
6377 
6378 	id = req->VolatileFileId;
6379 	ksmbd_session_rpc_close(work->sess, id);
6380 
6381 	rsp->StructureSize = cpu_to_le16(60);
6382 	rsp->Flags = 0;
6383 	rsp->Reserved = 0;
6384 	rsp->CreationTime = 0;
6385 	rsp->LastAccessTime = 0;
6386 	rsp->LastWriteTime = 0;
6387 	rsp->ChangeTime = 0;
6388 	rsp->AllocationSize = 0;
6389 	rsp->EndOfFile = 0;
6390 	rsp->Attributes = 0;
6391 
6392 	return ksmbd_iov_pin_rsp(work, (void *)rsp,
6393 				 sizeof(struct smb2_close_rsp));
6394 }
6395 
6396 /**
6397  * smb2_close() - handler for smb2 close file command
6398  * @work:	smb work containing close request buffer
6399  *
6400  * Return:	0 on success, otherwise error
6401  */
6402 int smb2_close(struct ksmbd_work *work)
6403 {
6404 	u64 volatile_id = KSMBD_NO_FID;
6405 	u64 sess_id;
6406 	struct smb2_close_req *req;
6407 	struct smb2_close_rsp *rsp;
6408 	struct ksmbd_conn *conn = work->conn;
6409 	struct ksmbd_file *fp;
6410 	u64 time;
6411 	int err = 0;
6412 
6413 	ksmbd_debug(SMB, "Received smb2 close request\n");
6414 
6415 	WORK_BUFFERS(work, req, rsp);
6416 
6417 	if (smb2_compound_has_failed(work, &rsp->hdr))
6418 		return -EACCES;
6419 
6420 	if (test_share_config_flag(work->tcon->share_conf,
6421 				   KSMBD_SHARE_FLAG_PIPE)) {
6422 		ksmbd_debug(SMB, "IPC pipe close request\n");
6423 		return smb2_close_pipe(work);
6424 	}
6425 
6426 	sess_id = le64_to_cpu(req->hdr.SessionId);
6427 	if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
6428 		sess_id = work->compound_sid;
6429 
6430 	work->compound_sid = 0;
6431 	if (check_session_id(conn, sess_id)) {
6432 		work->compound_sid = sess_id;
6433 	} else {
6434 		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
6435 		if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
6436 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6437 		err = -EBADF;
6438 		goto out;
6439 	}
6440 
6441 	if (work->next_smb2_rcv_hdr_off &&
6442 	    !has_file_id(req->VolatileFileId)) {
6443 		if (!has_file_id(work->compound_fid)) {
6444 			/* file already closed, return FILE_CLOSED */
6445 			ksmbd_debug(SMB, "file already closed\n");
6446 			rsp->hdr.Status = STATUS_FILE_CLOSED;
6447 			err = -EBADF;
6448 			goto out;
6449 		} else {
6450 			ksmbd_debug(SMB,
6451 				    "Compound request set FID = %llu:%llu\n",
6452 				    work->compound_fid,
6453 				    work->compound_pfid);
6454 			volatile_id = work->compound_fid;
6455 
6456 			/* file closed, stored id is not valid anymore */
6457 			work->compound_fid = KSMBD_NO_FID;
6458 			work->compound_pfid = KSMBD_NO_FID;
6459 		}
6460 	} else {
6461 		volatile_id = req->VolatileFileId;
6462 	}
6463 	ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
6464 
6465 	rsp->StructureSize = cpu_to_le16(60);
6466 	rsp->Reserved = 0;
6467 
6468 	if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
6469 		struct kstat stat;
6470 		int ret;
6471 
6472 		fp = ksmbd_lookup_fd_fast(work, volatile_id);
6473 		if (!fp) {
6474 			err = -ENOENT;
6475 			goto out;
6476 		}
6477 
6478 		ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6479 				  AT_STATX_SYNC_AS_STAT);
6480 		if (ret) {
6481 			ksmbd_fd_put(work, fp);
6482 			goto out;
6483 		}
6484 
6485 		rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
6486 		rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
6487 		rsp->EndOfFile = cpu_to_le64(stat.size);
6488 		rsp->Attributes = fp->f_ci->m_fattr;
6489 		rsp->CreationTime = cpu_to_le64(fp->create_time);
6490 		time = ksmbd_UnixTimeToNT(stat.atime);
6491 		rsp->LastAccessTime = cpu_to_le64(time);
6492 		time = ksmbd_UnixTimeToNT(stat.mtime);
6493 		if (time > fp->open_mtime &&
6494 		    time - fp->open_mtime < KSMBD_WRITE_TIME_RESOLUTION)
6495 			time = fp->open_mtime;
6496 		rsp->LastWriteTime = cpu_to_le64(time);
6497 		rsp->ChangeTime = cpu_to_le64(fp->change_time);
6498 		ksmbd_fd_put(work, fp);
6499 	} else {
6500 		rsp->Flags = 0;
6501 		rsp->AllocationSize = 0;
6502 		rsp->EndOfFile = 0;
6503 		rsp->Attributes = 0;
6504 		rsp->CreationTime = 0;
6505 		rsp->LastAccessTime = 0;
6506 		rsp->LastWriteTime = 0;
6507 		rsp->ChangeTime = 0;
6508 	}
6509 
6510 	err = ksmbd_close_fd(work, volatile_id);
6511 out:
6512 	if (!err)
6513 		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6514 					sizeof(struct smb2_close_rsp));
6515 
6516 	if (err) {
6517 		if (rsp->hdr.Status == 0)
6518 			rsp->hdr.Status = STATUS_FILE_CLOSED;
6519 		smb2_set_err_rsp(work);
6520 	}
6521 
6522 	return err;
6523 }
6524 
6525 /**
6526  * smb2_echo() - handler for smb2 echo(ping) command
6527  * @work:	smb work containing echo request buffer
6528  *
6529  * Return:	0 on success, otherwise error
6530  */
6531 int smb2_echo(struct ksmbd_work *work)
6532 {
6533 	struct smb2_echo_rsp *rsp = smb_get_msg(work->response_buf);
6534 
6535 	ksmbd_debug(SMB, "Received smb2 echo request\n");
6536 
6537 	if (work->next_smb2_rcv_hdr_off)
6538 		rsp = ksmbd_resp_buf_next(work);
6539 
6540 	rsp->StructureSize = cpu_to_le16(4);
6541 	rsp->Reserved = 0;
6542 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
6543 }
6544 
6545 static int smb2_rename(struct ksmbd_work *work,
6546 		       struct ksmbd_file *fp,
6547 		       struct smb2_file_rename_info *file_info,
6548 		       struct nls_table *local_nls)
6549 {
6550 	struct ksmbd_share_config *share = fp->tcon->share_conf;
6551 	char *new_name = NULL;
6552 	int rc, flags = 0;
6553 
6554 	ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
6555 	new_name = smb2_get_name(file_info->FileName,
6556 				 le32_to_cpu(file_info->FileNameLength),
6557 				 local_nls);
6558 	if (IS_ERR(new_name))
6559 		return PTR_ERR(new_name);
6560 
6561 	if (fp->is_posix_ctxt == false && strchr(new_name, ':')) {
6562 		int s_type;
6563 		char *xattr_stream_name, *stream_name = NULL;
6564 		size_t xattr_stream_size;
6565 		int len;
6566 
6567 		rc = parse_stream_name(new_name, &stream_name, &s_type);
6568 		if (rc < 0)
6569 			goto out;
6570 
6571 		len = strlen(new_name);
6572 		if (len > 0 && new_name[len - 1] != '/') {
6573 			pr_err("not allow base filename in rename\n");
6574 			rc = -ESHARE;
6575 			goto out;
6576 		}
6577 
6578 		rc = ksmbd_vfs_xattr_stream_name(stream_name,
6579 						 &xattr_stream_name,
6580 						 &xattr_stream_size,
6581 						 s_type);
6582 		if (rc)
6583 			goto out;
6584 
6585 		rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
6586 					&fp->filp->f_path,
6587 					xattr_stream_name,
6588 					NULL, 0, 0, true);
6589 		if (rc < 0) {
6590 			pr_err("failed to store stream name in xattr: %d\n",
6591 			       rc);
6592 			rc = -EINVAL;
6593 		}
6594 		kfree(xattr_stream_name);
6595 		goto out;
6596 	}
6597 
6598 	ksmbd_debug(SMB, "new name %s\n", new_name);
6599 	if (ksmbd_share_veto_filename(share, new_name)) {
6600 		rc = -ENOENT;
6601 		ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
6602 		goto out;
6603 	}
6604 
6605 	if (!file_info->ReplaceIfExists)
6606 		flags = RENAME_NOREPLACE;
6607 
6608 	rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
6609 	if (!rc)
6610 		smb_break_all_levII_oplock(work, fp, 0);
6611 out:
6612 	kfree(new_name);
6613 	return rc;
6614 }
6615 
6616 static int smb2_create_link(struct ksmbd_work *work,
6617 			    struct ksmbd_share_config *share,
6618 			    struct smb2_file_link_info *file_info,
6619 			    unsigned int buf_len, struct file *filp,
6620 			    struct nls_table *local_nls)
6621 {
6622 	char *link_name = NULL, *target_name = NULL, *pathname = NULL;
6623 	struct path path;
6624 	int rc;
6625 
6626 	if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
6627 			le32_to_cpu(file_info->FileNameLength))
6628 		return -EINVAL;
6629 
6630 	ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
6631 	pathname = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
6632 	if (!pathname)
6633 		return -ENOMEM;
6634 
6635 	link_name = smb2_get_name(file_info->FileName,
6636 				  le32_to_cpu(file_info->FileNameLength),
6637 				  local_nls);
6638 	if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
6639 		rc = -EINVAL;
6640 		goto out;
6641 	}
6642 
6643 	ksmbd_debug(SMB, "link name is %s\n", link_name);
6644 	target_name = file_path(filp, pathname, PATH_MAX);
6645 	if (IS_ERR(target_name)) {
6646 		rc = -EINVAL;
6647 		goto out;
6648 	}
6649 
6650 	ksmbd_debug(SMB, "target name is %s\n", target_name);
6651 	rc = ksmbd_vfs_kern_path_start_removing(work, link_name, LOOKUP_NO_SYMLINKS,
6652 						&path, 0);
6653 	if (rc) {
6654 		if (rc != -ENOENT)
6655 			goto out;
6656 	} else {
6657 		if (file_info->ReplaceIfExists) {
6658 			rc = ksmbd_vfs_remove_file(work, &path);
6659 			if (rc) {
6660 				rc = -EINVAL;
6661 				ksmbd_debug(SMB, "cannot delete %s\n",
6662 					    link_name);
6663 			}
6664 		} else {
6665 			rc = -EEXIST;
6666 			ksmbd_debug(SMB, "link already exists\n");
6667 		}
6668 		ksmbd_vfs_kern_path_end_removing(&path);
6669 		if (rc)
6670 			goto out;
6671 	}
6672 	rc = ksmbd_vfs_link(work, target_name, link_name);
6673 	if (rc)
6674 		rc = -EINVAL;
6675 out:
6676 
6677 	if (!IS_ERR(link_name))
6678 		kfree(link_name);
6679 	kfree(pathname);
6680 	return rc;
6681 }
6682 
6683 static int set_file_basic_info(struct ksmbd_file *fp,
6684 			       struct file_basic_info *file_info,
6685 			       struct ksmbd_share_config *share)
6686 {
6687 	struct iattr attrs;
6688 	struct file *filp;
6689 	struct inode *inode;
6690 	struct mnt_idmap *idmap;
6691 	int rc = 0;
6692 
6693 	if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
6694 		return -EACCES;
6695 
6696 	attrs.ia_valid = 0;
6697 	filp = fp->filp;
6698 	inode = file_inode(filp);
6699 	idmap = file_mnt_idmap(filp);
6700 
6701 	if (file_info->CreationTime)
6702 		fp->create_time = le64_to_cpu(file_info->CreationTime);
6703 
6704 	if (file_info->LastAccessTime) {
6705 		attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
6706 		attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
6707 	}
6708 
6709 	if (file_info->ChangeTime) {
6710 		fp->change_time = le64_to_cpu(file_info->ChangeTime);
6711 		inode_set_ctime_to_ts(inode,
6712 				ksmbd_NTtimeToUnix(file_info->ChangeTime));
6713 	}
6714 
6715 	if (file_info->LastWriteTime) {
6716 		attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
6717 		attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME);
6718 	}
6719 
6720 	if (file_info->Attributes) {
6721 		if (!S_ISDIR(inode->i_mode) &&
6722 		    file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
6723 			pr_err("can't change a file to a directory\n");
6724 			return -EINVAL;
6725 		}
6726 
6727 		if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
6728 			fp->f_ci->m_fattr = file_info->Attributes |
6729 				(fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
6730 	}
6731 
6732 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
6733 	    (file_info->CreationTime || file_info->Attributes)) {
6734 		struct xattr_dos_attrib da = {0};
6735 
6736 		da.version = 4;
6737 		da.itime = fp->itime;
6738 		da.create_time = fp->create_time;
6739 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
6740 		da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
6741 			XATTR_DOSINFO_ITIME;
6742 
6743 		rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
6744 				true);
6745 		if (rc)
6746 			ksmbd_debug(SMB,
6747 				    "failed to restore file attribute in EA\n");
6748 		rc = 0;
6749 	}
6750 
6751 	if (attrs.ia_valid) {
6752 		struct dentry *dentry = filp->f_path.dentry;
6753 		struct inode *inode = d_inode(dentry);
6754 
6755 		if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
6756 			return -EACCES;
6757 
6758 		inode_lock(inode);
6759 		rc = notify_change(idmap, dentry, &attrs, NULL);
6760 		inode_unlock(inode);
6761 	}
6762 	return rc;
6763 }
6764 
6765 static int set_file_allocation_info(struct ksmbd_work *work,
6766 				    struct ksmbd_file *fp,
6767 				    struct smb2_file_alloc_info *file_alloc_info)
6768 {
6769 	/*
6770 	 * TODO : It's working fine only when store dos attributes
6771 	 * is not yes. need to implement a logic which works
6772 	 * properly with any smb.conf option
6773 	 */
6774 
6775 	loff_t alloc_blks;
6776 	u64 alloc_size;
6777 	struct inode *inode;
6778 	struct kstat stat;
6779 	int rc;
6780 
6781 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
6782 		return -EACCES;
6783 
6784 	if (ksmbd_stream_fd(fp) == true)
6785 		return 0;
6786 
6787 	rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6788 			 AT_STATX_SYNC_AS_STAT);
6789 	if (rc)
6790 		return rc;
6791 
6792 	/*
6793 	 * AllocationSize is fully client-controlled (the caller only
6794 	 * validates the fixed 8-byte buffer length). Reject values that
6795 	 * would overflow the "round up to 512-byte blocks" conversion
6796 	 * below instead of silently wrapping it to a tiny block count,
6797 	 * which would truncate the file to a size the client never
6798 	 * asked for.
6799 	 */
6800 	alloc_size = le64_to_cpu(file_alloc_info->AllocationSize);
6801 	if (alloc_size > MAX_LFS_FILESIZE - 511)
6802 		return -EINVAL;
6803 
6804 	alloc_blks = (alloc_size + 511) >> 9;
6805 	inode = file_inode(fp->filp);
6806 
6807 	if (alloc_blks > stat.blocks) {
6808 		smb_break_all_levII_oplock(work, fp, 1);
6809 		rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
6810 				   alloc_blks * 512);
6811 		if (rc && rc != -EOPNOTSUPP) {
6812 			pr_err("vfs_fallocate is failed : %d\n", rc);
6813 			return rc;
6814 		}
6815 	} else if (alloc_blks < stat.blocks) {
6816 		loff_t size;
6817 
6818 		/*
6819 		 * Allocation size could be smaller than original one
6820 		 * which means allocated blocks in file should be
6821 		 * deallocated. use truncate to cut out it, but inode
6822 		 * size is also updated with truncate offset.
6823 		 * inode size is retained by backup inode size.
6824 		 */
6825 		size = i_size_read(inode);
6826 		rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
6827 		if (rc) {
6828 			pr_err("truncate failed!, err %d\n", rc);
6829 			return rc;
6830 		}
6831 		if (size < alloc_blks * 512)
6832 			i_size_write(inode, size);
6833 	}
6834 
6835 	fp->allocation_size = le64_to_cpu(file_alloc_info->AllocationSize);
6836 	return 0;
6837 }
6838 
6839 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6840 				struct smb2_file_eof_info *file_eof_info)
6841 {
6842 	loff_t newsize;
6843 	struct inode *inode;
6844 	int rc;
6845 
6846 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
6847 		return -EACCES;
6848 
6849 	newsize = le64_to_cpu(file_eof_info->EndOfFile);
6850 	inode = file_inode(fp->filp);
6851 
6852 	/*
6853 	 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
6854 	 * on FAT32 shared device, truncate execution time is too long
6855 	 * and network error could cause from windows client. because
6856 	 * truncate of some filesystem like FAT32 fill zero data in
6857 	 * truncated range.
6858 	 */
6859 	if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC &&
6860 	    ksmbd_stream_fd(fp) == false) {
6861 		ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
6862 		rc = ksmbd_vfs_truncate(work, fp, newsize);
6863 		if (rc) {
6864 			ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
6865 			if (rc != -EAGAIN)
6866 				rc = -EBADF;
6867 			return rc;
6868 		}
6869 	}
6870 	return 0;
6871 }
6872 
6873 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6874 			   struct smb2_file_rename_info *rename_info,
6875 			   unsigned int buf_len)
6876 {
6877 	if (!(fp->daccess & FILE_DELETE_LE)) {
6878 		pr_err("no right to delete : 0x%x\n", fp->daccess);
6879 		return -EACCES;
6880 	}
6881 
6882 	if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
6883 			le32_to_cpu(rename_info->FileNameLength))
6884 		return -EINVAL;
6885 
6886 	if (!le32_to_cpu(rename_info->FileNameLength))
6887 		return -EINVAL;
6888 
6889 	return smb2_rename(work, fp, rename_info, work->conn->local_nls);
6890 }
6891 
6892 static int set_file_disposition_info(struct ksmbd_work *work,
6893 				     struct ksmbd_file *fp,
6894 				     struct smb2_file_disposition_info *file_info)
6895 {
6896 	struct inode *inode;
6897 
6898 	if (!(fp->daccess & FILE_DELETE_LE)) {
6899 		pr_err("no right to delete : 0x%x\n", fp->daccess);
6900 		return -EACCES;
6901 	}
6902 
6903 	inode = file_inode(fp->filp);
6904 	if (file_info->DeletePending) {
6905 		if (ksmbd_has_stream_without_delete_share(fp))
6906 			return -ESHARE;
6907 
6908 		if (S_ISDIR(inode->i_mode) &&
6909 		    ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
6910 			return -EBUSY;
6911 		smb_break_all_levII_oplock_for_delete(work, fp);
6912 		ksmbd_set_inode_pending_delete(fp);
6913 	} else {
6914 		ksmbd_clear_inode_pending_delete(fp);
6915 	}
6916 	return 0;
6917 }
6918 
6919 static int set_file_position_info(struct ksmbd_file *fp,
6920 				  struct smb2_file_pos_info *file_info)
6921 {
6922 	loff_t current_byte_offset;
6923 	unsigned long sector_size;
6924 	struct inode *inode;
6925 
6926 	inode = file_inode(fp->filp);
6927 	current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
6928 	sector_size = inode->i_sb->s_blocksize;
6929 
6930 	if (current_byte_offset < 0 ||
6931 	    (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
6932 	     current_byte_offset & (sector_size - 1))) {
6933 		pr_err("CurrentByteOffset is not valid : %llu\n",
6934 		       current_byte_offset);
6935 		return -EINVAL;
6936 	}
6937 
6938 	if (ksmbd_stream_fd(fp) == false)
6939 		fp->filp->f_pos = current_byte_offset;
6940 	else {
6941 		if (current_byte_offset > XATTR_SIZE_MAX)
6942 			current_byte_offset = XATTR_SIZE_MAX;
6943 		fp->stream.pos = current_byte_offset;
6944 	}
6945 	return 0;
6946 }
6947 
6948 static int set_file_mode_info(struct ksmbd_file *fp,
6949 			      struct smb2_file_mode_info *file_info)
6950 {
6951 	__le32 mode;
6952 
6953 	mode = file_info->Mode;
6954 
6955 	if ((mode & ~FILE_MODE_INFO_MASK)) {
6956 		pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
6957 		return -EINVAL;
6958 	}
6959 
6960 	/*
6961 	 * TODO : need to implement consideration for
6962 	 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
6963 	 */
6964 	ksmbd_vfs_set_fadvise(fp->filp, mode);
6965 	fp->coption = mode;
6966 	return 0;
6967 }
6968 
6969 /**
6970  * smb2_set_info_file() - handler for smb2 set info command
6971  * @work:	smb work containing set info command buffer
6972  * @fp:		ksmbd_file pointer
6973  * @req:	request buffer pointer
6974  * @share:	ksmbd_share_config pointer
6975  *
6976  * Return:	0 on success, otherwise error
6977  */
6978 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
6979 			      struct smb2_set_info_req *req,
6980 			      struct ksmbd_share_config *share)
6981 {
6982 	unsigned int buf_len = le32_to_cpu(req->BufferLength);
6983 	char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
6984 
6985 	switch (req->FileInfoClass) {
6986 	case FILE_BASIC_INFORMATION:
6987 	{
6988 		if (buf_len < sizeof(struct file_basic_info))
6989 			return -EMSGSIZE;
6990 
6991 		return set_file_basic_info(fp, (struct file_basic_info *)buffer, share);
6992 	}
6993 	case FILE_ALLOCATION_INFORMATION:
6994 	{
6995 		if (buf_len < sizeof(struct smb2_file_alloc_info))
6996 			return -EMSGSIZE;
6997 
6998 		return set_file_allocation_info(work, fp,
6999 						(struct smb2_file_alloc_info *)buffer);
7000 	}
7001 	case FILE_END_OF_FILE_INFORMATION:
7002 	{
7003 		if (buf_len < sizeof(struct smb2_file_eof_info))
7004 			return -EMSGSIZE;
7005 
7006 		return set_end_of_file_info(work, fp,
7007 					    (struct smb2_file_eof_info *)buffer);
7008 	}
7009 	case FILE_RENAME_INFORMATION:
7010 	{
7011 		if (buf_len < sizeof(struct smb2_file_rename_info))
7012 			return -EMSGSIZE;
7013 
7014 		return set_rename_info(work, fp,
7015 				       (struct smb2_file_rename_info *)buffer,
7016 				       buf_len);
7017 	}
7018 	case FILE_LINK_INFORMATION:
7019 	{
7020 		struct smb2_file_link_info *file_info;
7021 
7022 		if (buf_len < sizeof(struct smb2_file_link_info))
7023 			return -EMSGSIZE;
7024 
7025 		file_info = (struct smb2_file_link_info *)buffer;
7026 		if (file_info->ReplaceIfExists && !(fp->daccess & FILE_DELETE_LE)) {
7027 			pr_err("no right to delete : 0x%x\n", fp->daccess);
7028 			return -EACCES;
7029 		}
7030 
7031 		return smb2_create_link(work, work->tcon->share_conf, file_info,
7032 					buf_len, fp->filp,
7033 					work->conn->local_nls);
7034 	}
7035 	case FILE_DISPOSITION_INFORMATION:
7036 	{
7037 		if (buf_len < sizeof(struct smb2_file_disposition_info))
7038 			return -EMSGSIZE;
7039 
7040 		return set_file_disposition_info(work, fp,
7041 						 (struct smb2_file_disposition_info *)buffer);
7042 	}
7043 	case FILE_FULL_EA_INFORMATION:
7044 	{
7045 		if (!(fp->daccess & FILE_WRITE_EA_LE)) {
7046 			pr_err("Not permitted to write ext  attr: 0x%x\n",
7047 			       fp->daccess);
7048 			return -EACCES;
7049 		}
7050 
7051 		if (buf_len < sizeof(struct smb2_ea_info))
7052 			return -EMSGSIZE;
7053 
7054 		return smb2_set_ea((struct smb2_ea_info *)buffer,
7055 				   buf_len, &fp->filp->f_path, true);
7056 	}
7057 	case FILE_POSITION_INFORMATION:
7058 	{
7059 		if (buf_len < sizeof(struct smb2_file_pos_info))
7060 			return -EMSGSIZE;
7061 
7062 		return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
7063 	}
7064 	case FILE_MODE_INFORMATION:
7065 	{
7066 		if (buf_len < sizeof(struct smb2_file_mode_info))
7067 			return -EMSGSIZE;
7068 
7069 		return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
7070 	}
7071 	}
7072 
7073 	pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
7074 	return -EOPNOTSUPP;
7075 }
7076 
7077 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
7078 			     char *buffer, int buf_len)
7079 {
7080 	struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
7081 
7082 	fp->saccess |= FILE_SHARE_DELETE_LE;
7083 
7084 	if (!(fp->daccess & (FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE)))
7085 		return -EACCES;
7086 
7087 	return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
7088 			buf_len, false, true);
7089 }
7090 
7091 /**
7092  * smb2_set_info() - handler for smb2 set info command handler
7093  * @work:	smb work containing set info request buffer
7094  *
7095  * Return:	0 on success, otherwise error
7096  */
7097 int smb2_set_info(struct ksmbd_work *work)
7098 {
7099 	const struct cred *saved_cred;
7100 	struct smb2_set_info_req *req;
7101 	struct smb2_set_info_rsp *rsp;
7102 	struct ksmbd_file *fp = NULL;
7103 	int rc = 0;
7104 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7105 
7106 	ksmbd_debug(SMB, "Received smb2 set info request\n");
7107 
7108 	if (work->next_smb2_rcv_hdr_off) {
7109 		req = ksmbd_req_buf_next(work);
7110 		rsp = ksmbd_resp_buf_next(work);
7111 		if (smb2_compound_has_failed(work, &rsp->hdr))
7112 			return -EACCES;
7113 		if (!has_file_id(req->VolatileFileId)) {
7114 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7115 				    work->compound_fid);
7116 			id = work->compound_fid;
7117 			pid = work->compound_pfid;
7118 		}
7119 	} else {
7120 		req = smb_get_msg(work->request_buf);
7121 		rsp = smb_get_msg(work->response_buf);
7122 	}
7123 
7124 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7125 		ksmbd_debug(SMB, "User does not have write permission\n");
7126 		pr_err("User does not have write permission\n");
7127 		rc = -EACCES;
7128 		goto err_out;
7129 	}
7130 
7131 	if (!has_file_id(id)) {
7132 		id = req->VolatileFileId;
7133 		pid = req->PersistentFileId;
7134 	}
7135 
7136 	fp = ksmbd_lookup_fd_slow(work, id, pid);
7137 	if (!fp) {
7138 		ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
7139 		rc = -ENOENT;
7140 		goto err_out;
7141 	}
7142 
7143 	saved_cred = override_creds(fp->filp->f_cred);
7144 	switch (req->InfoType) {
7145 	case SMB2_O_INFO_FILE:
7146 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
7147 		rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
7148 		break;
7149 	case SMB2_O_INFO_SECURITY:
7150 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
7151 		rc = smb2_set_info_sec(fp,
7152 				       le32_to_cpu(req->AdditionalInformation),
7153 				       (char *)req + le16_to_cpu(req->BufferOffset),
7154 				       le32_to_cpu(req->BufferLength));
7155 		break;
7156 	default:
7157 		rc = -EOPNOTSUPP;
7158 	}
7159 	revert_creds(saved_cred);
7160 
7161 	if (rc < 0)
7162 		goto err_out;
7163 
7164 	rsp->StructureSize = cpu_to_le16(2);
7165 	rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
7166 			       sizeof(struct smb2_set_info_rsp));
7167 	if (rc)
7168 		goto err_out;
7169 	ksmbd_fd_put(work, fp);
7170 	return 0;
7171 
7172 err_out:
7173 	if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
7174 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
7175 	else if (rc == -EINVAL)
7176 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7177 	else if (rc == -EMSGSIZE)
7178 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
7179 	else if (rc == -ENOSPC || rc == -EFBIG)
7180 		rsp->hdr.Status = STATUS_DISK_FULL;
7181 	else if (rc == -ESHARE)
7182 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
7183 	else if (rc == -ENOENT)
7184 		rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
7185 	else if (rc == -EBUSY || rc == -ENOTEMPTY)
7186 		rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
7187 	else if (rc == -EAGAIN)
7188 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7189 	else if (rc == -EBADF || rc == -ESTALE)
7190 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
7191 	else if (rc == -EEXIST)
7192 		rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
7193 	else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
7194 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
7195 	smb2_set_err_rsp(work);
7196 	ksmbd_fd_put(work, fp);
7197 	ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
7198 	return rc;
7199 }
7200 
7201 /**
7202  * smb2_read_pipe() - handler for smb2 read from IPC pipe
7203  * @work:	smb work containing read IPC pipe command buffer
7204  *
7205  * Return:	0 on success, otherwise error
7206  */
7207 static noinline int smb2_read_pipe(struct ksmbd_work *work)
7208 {
7209 	int nbytes = 0, err;
7210 	u64 id;
7211 	struct ksmbd_rpc_command *rpc_resp;
7212 	struct smb2_read_req *req;
7213 	struct smb2_read_rsp *rsp;
7214 
7215 	WORK_BUFFERS(work, req, rsp);
7216 
7217 	id = req->VolatileFileId;
7218 
7219 	rpc_resp = ksmbd_rpc_read(work->sess, id);
7220 	if (rpc_resp) {
7221 		void *aux_payload_buf;
7222 
7223 		if (rpc_resp->flags != KSMBD_RPC_OK) {
7224 			err = -EINVAL;
7225 			goto out;
7226 		}
7227 
7228 		aux_payload_buf =
7229 			kvmalloc(rpc_resp->payload_sz, KSMBD_DEFAULT_GFP);
7230 		if (!aux_payload_buf) {
7231 			err = -ENOMEM;
7232 			goto out;
7233 		}
7234 
7235 		memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
7236 
7237 		nbytes = rpc_resp->payload_sz;
7238 		err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
7239 					     offsetof(struct smb2_read_rsp, Buffer),
7240 					     aux_payload_buf, nbytes);
7241 		if (err) {
7242 			kvfree(aux_payload_buf);
7243 			goto out;
7244 		}
7245 		kvfree(rpc_resp);
7246 	} else {
7247 		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
7248 					offsetof(struct smb2_read_rsp, Buffer));
7249 		if (err)
7250 			goto out;
7251 	}
7252 
7253 	rsp->StructureSize = cpu_to_le16(17);
7254 	rsp->DataOffset = 80;
7255 	rsp->Reserved = 0;
7256 	rsp->DataLength = cpu_to_le32(nbytes);
7257 	rsp->DataRemaining = 0;
7258 	rsp->Flags = 0;
7259 	return 0;
7260 
7261 out:
7262 	rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7263 	smb2_set_err_rsp(work);
7264 	kvfree(rpc_resp);
7265 	return err;
7266 }
7267 
7268 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
7269 					struct smbdirect_buffer_descriptor_v1 *desc,
7270 					__le32 Channel,
7271 					__le16 ChannelInfoLength)
7272 {
7273 	unsigned int i, ch_count;
7274 
7275 	if (work->conn->dialect == SMB30_PROT_ID &&
7276 	    Channel != SMB2_CHANNEL_RDMA_V1)
7277 		return -EINVAL;
7278 
7279 	ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
7280 	if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
7281 		for (i = 0; i < ch_count; i++) {
7282 			pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
7283 				i,
7284 				le32_to_cpu(desc[i].token),
7285 				le32_to_cpu(desc[i].length));
7286 		}
7287 	}
7288 	if (!ch_count)
7289 		return -EINVAL;
7290 
7291 	work->need_invalidate_rkey =
7292 		(Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
7293 	if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
7294 		work->remote_key = le32_to_cpu(desc->token);
7295 	return 0;
7296 }
7297 
7298 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
7299 				      struct smb2_read_req *req, void *data_buf,
7300 				      size_t length)
7301 {
7302 	int err;
7303 
7304 	err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
7305 				    (struct smbdirect_buffer_descriptor_v1 *)
7306 				    ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
7307 				    le16_to_cpu(req->ReadChannelInfoLength));
7308 	if (err)
7309 		return err;
7310 
7311 	return length;
7312 }
7313 
7314 /**
7315  * smb2_read() - handler for smb2 read from file
7316  * @work:	smb work containing read command buffer
7317  *
7318  * Return:	0 on success, otherwise error
7319  */
7320 int smb2_read(struct ksmbd_work *work)
7321 {
7322 	struct ksmbd_conn *conn = work->conn;
7323 	struct smb2_read_req *req;
7324 	struct smb2_read_rsp *rsp;
7325 	struct ksmbd_file *fp = NULL;
7326 	loff_t offset;
7327 	size_t length, mincount;
7328 	ssize_t nbytes = 0, remain_bytes = 0;
7329 	int err = 0;
7330 	bool is_rdma_channel = false, async_interim = false;
7331 	unsigned int max_read_size = conn->vals->max_read_size;
7332 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7333 	void *aux_payload_buf;
7334 
7335 	ksmbd_debug(SMB, "Received smb2 read request\n");
7336 
7337 	if (test_share_config_flag(work->tcon->share_conf,
7338 				   KSMBD_SHARE_FLAG_PIPE)) {
7339 		ksmbd_debug(SMB, "IPC pipe read request\n");
7340 		return smb2_read_pipe(work);
7341 	}
7342 
7343 	if (work->next_smb2_rcv_hdr_off) {
7344 		req = ksmbd_req_buf_next(work);
7345 		rsp = ksmbd_resp_buf_next(work);
7346 		if (smb2_compound_has_failed(work, &rsp->hdr))
7347 			return -EACCES;
7348 		if (!has_file_id(req->VolatileFileId)) {
7349 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7350 					work->compound_fid);
7351 			id = work->compound_fid;
7352 			pid = work->compound_pfid;
7353 		}
7354 	} else {
7355 		req = smb_get_msg(work->request_buf);
7356 		rsp = smb_get_msg(work->response_buf);
7357 	}
7358 
7359 	if (!has_file_id(id)) {
7360 		id = req->VolatileFileId;
7361 		pid = req->PersistentFileId;
7362 	}
7363 
7364 	if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
7365 	    req->Channel == SMB2_CHANNEL_RDMA_V1) {
7366 		is_rdma_channel = true;
7367 		max_read_size = get_smbd_max_read_write_size(work->conn->transport);
7368 		if (max_read_size == 0) {
7369 			err = -EINVAL;
7370 			goto out;
7371 		}
7372 	}
7373 
7374 	if (is_rdma_channel == true) {
7375 		unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
7376 
7377 		if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
7378 			err = -EINVAL;
7379 			goto out;
7380 		}
7381 		err = smb2_set_remote_key_for_rdma(work,
7382 						   (struct smbdirect_buffer_descriptor_v1 *)
7383 						   ((char *)req + ch_offset),
7384 						   req->Channel,
7385 						   req->ReadChannelInfoLength);
7386 		if (err)
7387 			goto out;
7388 	}
7389 
7390 	fp = ksmbd_lookup_fd_slow(work, id, pid);
7391 	if (!fp) {
7392 		err = -ENOENT;
7393 		goto out;
7394 	}
7395 
7396 	if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
7397 		pr_err("Not permitted to read : 0x%x\n", fp->daccess);
7398 		err = -EACCES;
7399 		goto out;
7400 	}
7401 
7402 	if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
7403 		err = setup_async_work(work, NULL, NULL);
7404 		if (err)
7405 			goto out;
7406 		smb2_send_interim_resp(work, STATUS_PENDING);
7407 		async_interim = true;
7408 	}
7409 
7410 	offset = le64_to_cpu(req->Offset);
7411 	if (offset < 0) {
7412 		err = -EINVAL;
7413 		goto out;
7414 	}
7415 	length = le32_to_cpu(req->Length);
7416 	mincount = le32_to_cpu(req->MinimumCount);
7417 
7418 	if (length > max_read_size) {
7419 		ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
7420 			    max_read_size);
7421 		err = -EINVAL;
7422 		goto out;
7423 	}
7424 
7425 	ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
7426 		    fp->filp, offset, length);
7427 
7428 	aux_payload_buf = kvmalloc(ALIGN(length, 8), KSMBD_DEFAULT_GFP);
7429 	if (!aux_payload_buf) {
7430 		err = -ENOMEM;
7431 		goto out;
7432 	}
7433 
7434 	nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
7435 	if (nbytes < 0) {
7436 		kvfree(aux_payload_buf);
7437 		err = nbytes;
7438 		goto out;
7439 	}
7440 
7441 	/*
7442 	 * ksmbd_vfs_read() fills only nbytes; the [nbytes, ALIGN(nbytes, 8))
7443 	 * tail of the un-zeroed buffer is transmitted as compound-response
7444 	 * alignment padding, leaking uninitialized kernel memory to the
7445 	 * client.  Zero just that tail.
7446 	 */
7447 	if (nbytes & 7)
7448 		memset(aux_payload_buf + nbytes, 0, ALIGN(nbytes, 8) - nbytes);
7449 
7450 	if ((nbytes == 0 && length != 0) || nbytes < mincount) {
7451 		kvfree(aux_payload_buf);
7452 		rsp->hdr.Status = STATUS_END_OF_FILE;
7453 		smb2_set_err_rsp(work);
7454 		if (async_interim)
7455 			release_async_work(work);
7456 		ksmbd_fd_put(work, fp);
7457 		return -ENODATA;
7458 	}
7459 
7460 	ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
7461 		    nbytes, offset, mincount);
7462 
7463 	if (is_rdma_channel == true) {
7464 		/* write data to the client using rdma channel */
7465 		remain_bytes = smb2_read_rdma_channel(work, req,
7466 						      aux_payload_buf,
7467 						      nbytes);
7468 		kvfree(aux_payload_buf);
7469 		aux_payload_buf = NULL;
7470 		nbytes = 0;
7471 		if (remain_bytes < 0) {
7472 			err = (int)remain_bytes;
7473 			goto out;
7474 		}
7475 	}
7476 
7477 	rsp->StructureSize = cpu_to_le16(17);
7478 	rsp->DataOffset = 80;
7479 	rsp->Reserved = 0;
7480 	rsp->DataLength = cpu_to_le32(nbytes);
7481 	rsp->DataRemaining = cpu_to_le32(remain_bytes);
7482 	rsp->Flags = 0;
7483 	err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
7484 				     offsetof(struct smb2_read_rsp, Buffer),
7485 				     aux_payload_buf, nbytes);
7486 	if (err) {
7487 		kvfree(aux_payload_buf);
7488 		goto out;
7489 	}
7490 	if (async_interim)
7491 		release_async_work(work);
7492 	/*
7493 	 * RDMA responses are transferred through channel buffers and encrypted
7494 	 * responses use the encryption transform, so only normal SMB transport
7495 	 * responses are candidates for compression.
7496 	 */
7497 	if (!is_rdma_channel && nbytes &&
7498 	    (req->Flags & SMB2_READFLAG_REQUEST_COMPRESSED) &&
7499 	    conn->compress_algorithm != SMB3_COMPRESS_NONE)
7500 		work->compress_response = true;
7501 	ksmbd_fd_put(work, fp);
7502 	return 0;
7503 
7504 out:
7505 	if (async_interim)
7506 		release_async_work(work);
7507 	if (err) {
7508 		if (err == -EISDIR)
7509 			rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
7510 		else if (err == -EAGAIN)
7511 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7512 		else if (err == -ENOENT)
7513 			rsp->hdr.Status = STATUS_FILE_CLOSED;
7514 		else if (err == -EACCES)
7515 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
7516 		else if (err == -ESHARE)
7517 			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
7518 		else if (err == -EINVAL)
7519 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7520 		else
7521 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
7522 
7523 		smb2_set_err_rsp(work);
7524 	}
7525 	ksmbd_fd_put(work, fp);
7526 	return err;
7527 }
7528 
7529 /**
7530  * smb2_write_pipe() - handler for smb2 write on IPC pipe
7531  * @work:	smb work containing write IPC pipe command buffer
7532  *
7533  * Return:	0 on success, otherwise error
7534  */
7535 static noinline int smb2_write_pipe(struct ksmbd_work *work)
7536 {
7537 	struct smb2_write_req *req;
7538 	struct smb2_write_rsp *rsp;
7539 	struct ksmbd_rpc_command *rpc_resp;
7540 	u64 id = 0;
7541 	int err = 0, ret = 0;
7542 	char *data_buf;
7543 	size_t length;
7544 
7545 	WORK_BUFFERS(work, req, rsp);
7546 
7547 	length = le32_to_cpu(req->Length);
7548 	id = req->VolatileFileId;
7549 
7550 	if ((u64)le16_to_cpu(req->DataOffset) + length >
7551 	    get_rfc1002_len(work->request_buf)) {
7552 		pr_err("invalid write data offset %u, smb_len %u\n",
7553 		       le16_to_cpu(req->DataOffset),
7554 		       get_rfc1002_len(work->request_buf));
7555 		err = -EINVAL;
7556 		goto out;
7557 	}
7558 
7559 	data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
7560 			   le16_to_cpu(req->DataOffset));
7561 
7562 	rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
7563 	if (rpc_resp) {
7564 		if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7565 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7566 			kvfree(rpc_resp);
7567 			smb2_set_err_rsp(work);
7568 			return -EOPNOTSUPP;
7569 		}
7570 		if (rpc_resp->flags != KSMBD_RPC_OK) {
7571 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
7572 			smb2_set_err_rsp(work);
7573 			kvfree(rpc_resp);
7574 			return ret;
7575 		}
7576 		kvfree(rpc_resp);
7577 	}
7578 
7579 	rsp->StructureSize = cpu_to_le16(17);
7580 	rsp->DataOffset = 0;
7581 	rsp->Reserved = 0;
7582 	rsp->DataLength = cpu_to_le32(length);
7583 	rsp->DataRemaining = 0;
7584 	rsp->Reserved2 = 0;
7585 	err = ksmbd_iov_pin_rsp(work, (void *)rsp,
7586 				offsetof(struct smb2_write_rsp, Buffer));
7587 out:
7588 	if (err) {
7589 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
7590 		smb2_set_err_rsp(work);
7591 	}
7592 
7593 	return err;
7594 }
7595 
7596 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
7597 				       struct smb2_write_req *req,
7598 				       struct ksmbd_file *fp,
7599 				       loff_t offset, size_t length, bool sync)
7600 {
7601 	char *data_buf;
7602 	int ret;
7603 	ssize_t nbytes;
7604 
7605 	data_buf = kvzalloc(length, KSMBD_DEFAULT_GFP);
7606 	if (!data_buf)
7607 		return -ENOMEM;
7608 
7609 	ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
7610 				   (struct smbdirect_buffer_descriptor_v1 *)
7611 				   ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
7612 				   le16_to_cpu(req->WriteChannelInfoLength));
7613 	if (ret < 0) {
7614 		kvfree(data_buf);
7615 		return ret;
7616 	}
7617 
7618 	ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
7619 	kvfree(data_buf);
7620 	if (ret < 0)
7621 		return ret;
7622 
7623 	return nbytes;
7624 }
7625 
7626 /**
7627  * smb2_write() - handler for smb2 write from file
7628  * @work:	smb work containing write command buffer
7629  *
7630  * Return:	0 on success, otherwise error
7631  */
7632 int smb2_write(struct ksmbd_work *work)
7633 {
7634 	struct smb2_write_req *req;
7635 	struct smb2_write_rsp *rsp;
7636 	struct ksmbd_file *fp = NULL;
7637 	loff_t offset;
7638 	size_t length;
7639 	ssize_t nbytes;
7640 	char *data_buf;
7641 	bool writethrough = false, is_rdma_channel = false;
7642 	bool async_interim = false;
7643 	int err = 0;
7644 	unsigned int max_write_size = work->conn->vals->max_write_size;
7645 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7646 
7647 	ksmbd_debug(SMB, "Received smb2 write request\n");
7648 
7649 	WORK_BUFFERS(work, req, rsp);
7650 
7651 	if (smb2_compound_has_failed(work, &rsp->hdr))
7652 		return -EACCES;
7653 
7654 	if (work->next_smb2_rcv_hdr_off &&
7655 	    !has_file_id(req->VolatileFileId)) {
7656 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7657 			    work->compound_fid);
7658 		id = work->compound_fid;
7659 		pid = work->compound_pfid;
7660 	}
7661 
7662 	if (!has_file_id(id)) {
7663 		id = req->VolatileFileId;
7664 		pid = req->PersistentFileId;
7665 	}
7666 
7667 	if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
7668 		ksmbd_debug(SMB, "IPC pipe write request\n");
7669 		return smb2_write_pipe(work);
7670 	}
7671 
7672 	offset = le64_to_cpu(req->Offset);
7673 	if (offset < 0)
7674 		return -EINVAL;
7675 	length = le32_to_cpu(req->Length);
7676 
7677 	if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
7678 	    req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
7679 		is_rdma_channel = true;
7680 		max_write_size = get_smbd_max_read_write_size(work->conn->transport);
7681 		if (max_write_size == 0) {
7682 			err = -EINVAL;
7683 			goto out;
7684 		}
7685 		length = le32_to_cpu(req->RemainingBytes);
7686 	}
7687 
7688 	if (is_rdma_channel == true) {
7689 		unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
7690 
7691 		if (req->Length != 0 || req->DataOffset != 0 ||
7692 		    ch_offset < offsetof(struct smb2_write_req, Buffer)) {
7693 			err = -EINVAL;
7694 			goto out;
7695 		}
7696 		err = smb2_set_remote_key_for_rdma(work,
7697 						   (struct smbdirect_buffer_descriptor_v1 *)
7698 						   ((char *)req + ch_offset),
7699 						   req->Channel,
7700 						   req->WriteChannelInfoLength);
7701 		if (err)
7702 			goto out;
7703 	}
7704 
7705 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7706 		ksmbd_debug(SMB, "User does not have write permission\n");
7707 		err = -EACCES;
7708 		goto out;
7709 	}
7710 
7711 	fp = ksmbd_lookup_fd_slow(work, id, pid);
7712 	if (!fp) {
7713 		err = -ENOENT;
7714 		goto out;
7715 	}
7716 
7717 	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
7718 		pr_err("Not permitted to write : 0x%x\n", fp->daccess);
7719 		err = -EACCES;
7720 		goto out;
7721 	}
7722 
7723 	if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
7724 		err = setup_async_work(work, NULL, NULL);
7725 		if (err)
7726 			goto out;
7727 		smb2_send_interim_resp(work, STATUS_PENDING);
7728 		async_interim = true;
7729 	}
7730 
7731 	if (length > max_write_size) {
7732 		ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
7733 			    max_write_size);
7734 		err = -EINVAL;
7735 		goto out;
7736 	}
7737 
7738 	ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
7739 	if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
7740 		writethrough = true;
7741 
7742 	if (is_rdma_channel == false) {
7743 		if (le16_to_cpu(req->DataOffset) <
7744 		    offsetof(struct smb2_write_req, Buffer)) {
7745 			err = -EINVAL;
7746 			goto out;
7747 		}
7748 
7749 		data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
7750 				    le16_to_cpu(req->DataOffset));
7751 
7752 		ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
7753 			    fp->filp, offset, length);
7754 		err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
7755 				      writethrough, &nbytes);
7756 		if (err < 0)
7757 			goto out;
7758 	} else {
7759 		/* read data from the client using rdma channel, and
7760 		 * write the data.
7761 		 */
7762 		nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
7763 						 writethrough);
7764 		if (nbytes < 0) {
7765 			err = (int)nbytes;
7766 			goto out;
7767 		}
7768 	}
7769 
7770 	rsp->StructureSize = cpu_to_le16(17);
7771 	rsp->DataOffset = 0;
7772 	rsp->Reserved = 0;
7773 	rsp->DataLength = cpu_to_le32(nbytes);
7774 	rsp->DataRemaining = 0;
7775 	rsp->Reserved2 = 0;
7776 	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
7777 	if (err)
7778 		goto out;
7779 	if (async_interim)
7780 		release_async_work(work);
7781 	ksmbd_fd_put(work, fp);
7782 	return 0;
7783 
7784 out:
7785 	if (async_interim)
7786 		release_async_work(work);
7787 
7788 	if (err == -EAGAIN)
7789 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7790 	else if (err == -ENOSPC || err == -EFBIG)
7791 		rsp->hdr.Status = STATUS_DISK_FULL;
7792 	else if (err == -ENOENT)
7793 		rsp->hdr.Status = STATUS_FILE_CLOSED;
7794 	else if (err == -EACCES)
7795 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
7796 	else if (err == -ESHARE)
7797 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
7798 	else if (err == -EINVAL)
7799 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7800 	else
7801 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
7802 
7803 	smb2_set_err_rsp(work);
7804 	ksmbd_fd_put(work, fp);
7805 	return err;
7806 }
7807 
7808 /**
7809  * smb2_flush() - handler for smb2 flush file - fsync
7810  * @work:	smb work containing flush command buffer
7811  *
7812  * Return:	0 on success, otherwise error
7813  */
7814 int smb2_flush(struct ksmbd_work *work)
7815 {
7816 	struct smb2_flush_req *req;
7817 	struct smb2_flush_rsp *rsp;
7818 	u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7819 	int err;
7820 
7821 	WORK_BUFFERS(work, req, rsp);
7822 
7823 	ksmbd_debug(SMB, "Received smb2 flush request(fid : %llu)\n", req->VolatileFileId);
7824 
7825 	if (smb2_compound_has_failed(work, &rsp->hdr))
7826 		return -EACCES;
7827 
7828 	if (work->next_smb2_rcv_hdr_off &&
7829 	    !has_file_id(req->VolatileFileId)) {
7830 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7831 			    work->compound_fid);
7832 		id = work->compound_fid;
7833 		pid = work->compound_pfid;
7834 	}
7835 
7836 	if (!has_file_id(id)) {
7837 		id = req->VolatileFileId;
7838 		pid = req->PersistentFileId;
7839 	}
7840 
7841 	err = ksmbd_vfs_fsync(work, id, pid);
7842 	if (err)
7843 		goto out;
7844 
7845 	rsp->StructureSize = cpu_to_le16(4);
7846 	rsp->Reserved = 0;
7847 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
7848 
7849 out:
7850 	rsp->hdr.Status = STATUS_INVALID_HANDLE;
7851 	smb2_set_err_rsp(work);
7852 	return err;
7853 }
7854 
7855 /**
7856  * smb2_cancel() - handler for smb2 cancel command
7857  * @work:	smb work containing cancel command buffer
7858  *
7859  * Return:	0 on success, otherwise error
7860  */
7861 int smb2_cancel(struct ksmbd_work *work)
7862 {
7863 	struct ksmbd_conn *conn = work->conn;
7864 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
7865 	struct smb2_hdr *chdr;
7866 	struct ksmbd_work *iter;
7867 	struct list_head *command_list;
7868 
7869 	if (work->next_smb2_rcv_hdr_off)
7870 		hdr = ksmbd_resp_buf_next(work);
7871 
7872 	ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
7873 		    le64_to_cpu(hdr->MessageId),
7874 		    le32_to_cpu(hdr->Flags));
7875 
7876 	if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
7877 		command_list = &conn->async_requests;
7878 
7879 		spin_lock(&conn->request_lock);
7880 		list_for_each_entry(iter, command_list,
7881 				    async_request_entry) {
7882 			chdr = smb_get_msg(iter->request_buf);
7883 
7884 			if (iter->async_id !=
7885 			    le64_to_cpu(hdr->Id.AsyncId))
7886 				continue;
7887 
7888 			/*
7889 			 * Only an ACTIVE deferred work may have its cancel_fn
7890 			 * fired.  A CANCELLED or CLOSED work already took the
7891 			 * smb2_lock() non-ACTIVE early-exit that frees the
7892 			 * file_lock and skips release_async_work(), so it is
7893 			 * still on conn->async_requests with a live cancel_fn
7894 			 * pointing at the freed file_lock.
7895 			 */
7896 			if (iter->state != KSMBD_WORK_ACTIVE)
7897 				break;
7898 
7899 			ksmbd_debug(SMB,
7900 				    "smb2 with AsyncId %llu cancelled command = 0x%x\n",
7901 				    le64_to_cpu(hdr->Id.AsyncId),
7902 				    le16_to_cpu(chdr->Command));
7903 			iter->state = KSMBD_WORK_CANCELLED;
7904 			if (iter->cancel_fn)
7905 				iter->cancel_fn(iter->cancel_argv);
7906 			break;
7907 		}
7908 		spin_unlock(&conn->request_lock);
7909 	} else {
7910 		command_list = &conn->requests;
7911 
7912 		spin_lock(&conn->request_lock);
7913 		list_for_each_entry(iter, command_list, request_entry) {
7914 			chdr = smb_get_msg(iter->request_buf);
7915 
7916 			if (chdr->MessageId != hdr->MessageId ||
7917 			    iter == work)
7918 				continue;
7919 
7920 			ksmbd_debug(SMB,
7921 				    "smb2 with mid %llu cancelled command = 0x%x\n",
7922 				    le64_to_cpu(hdr->MessageId),
7923 				    le16_to_cpu(chdr->Command));
7924 			iter->state = KSMBD_WORK_CANCELLED;
7925 			break;
7926 		}
7927 		spin_unlock(&conn->request_lock);
7928 	}
7929 
7930 	/* For SMB2_CANCEL command itself send no response*/
7931 	work->send_no_response = 1;
7932 	return 0;
7933 }
7934 
7935 struct file_lock *smb_flock_init(struct file *f)
7936 {
7937 	struct file_lock *fl;
7938 
7939 	fl = locks_alloc_lock();
7940 	if (!fl)
7941 		goto out;
7942 
7943 	locks_init_lock(fl);
7944 
7945 	fl->c.flc_owner = f;
7946 	fl->c.flc_pid = current->tgid;
7947 	fl->c.flc_file = f;
7948 	fl->c.flc_flags = FL_POSIX;
7949 	fl->fl_ops = NULL;
7950 	fl->fl_lmops = NULL;
7951 
7952 out:
7953 	return fl;
7954 }
7955 
7956 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
7957 {
7958 	int cmd = -EINVAL;
7959 
7960 	/* Checking for wrong flag combination during lock request*/
7961 	switch (flags) {
7962 	case SMB2_LOCKFLAG_SHARED:
7963 		ksmbd_debug(SMB, "received shared request\n");
7964 		cmd = F_SETLKW;
7965 		flock->c.flc_type = F_RDLCK;
7966 		flock->c.flc_flags |= FL_SLEEP;
7967 		break;
7968 	case SMB2_LOCKFLAG_EXCLUSIVE:
7969 		ksmbd_debug(SMB, "received exclusive request\n");
7970 		cmd = F_SETLKW;
7971 		flock->c.flc_type = F_WRLCK;
7972 		flock->c.flc_flags |= FL_SLEEP;
7973 		break;
7974 	case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7975 		ksmbd_debug(SMB,
7976 			    "received shared & fail immediately request\n");
7977 		cmd = F_SETLK;
7978 		flock->c.flc_type = F_RDLCK;
7979 		break;
7980 	case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7981 		ksmbd_debug(SMB,
7982 			    "received exclusive & fail immediately request\n");
7983 		cmd = F_SETLK;
7984 		flock->c.flc_type = F_WRLCK;
7985 		break;
7986 	case SMB2_LOCKFLAG_UNLOCK:
7987 		ksmbd_debug(SMB, "received unlock request\n");
7988 		flock->c.flc_type = F_UNLCK;
7989 		cmd = F_SETLK;
7990 		break;
7991 	}
7992 
7993 	return cmd;
7994 }
7995 
7996 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
7997 					 unsigned int cmd, int flags,
7998 					 struct list_head *lock_list)
7999 {
8000 	struct ksmbd_lock *lock;
8001 
8002 	lock = kzalloc_obj(struct ksmbd_lock, KSMBD_DEFAULT_GFP);
8003 	if (!lock)
8004 		return NULL;
8005 
8006 	lock->cmd = cmd;
8007 	lock->fl = flock;
8008 	lock->start = flock->fl_start;
8009 	lock->end = flock->fl_end;
8010 	lock->flags = flags;
8011 	if (lock->start == lock->end)
8012 		lock->zero_len = 1;
8013 	INIT_LIST_HEAD(&lock->clist);
8014 	INIT_LIST_HEAD(&lock->flist);
8015 	INIT_LIST_HEAD(&lock->llist);
8016 	list_add_tail(&lock->llist, lock_list);
8017 
8018 	return lock;
8019 }
8020 
8021 static void smb2_remove_blocked_lock(void **argv)
8022 {
8023 	struct file_lock *flock = (struct file_lock *)argv[0];
8024 
8025 	ksmbd_vfs_posix_lock_unblock(flock);
8026 	locks_wake_up(flock);
8027 }
8028 
8029 static inline bool lock_defer_pending(struct file_lock *fl)
8030 {
8031 	/* check pending lock waiters */
8032 	return waitqueue_active(&fl->c.flc_wait);
8033 }
8034 
8035 /**
8036  * smb2_lock() - handler for smb2 file lock command
8037  * @work:	smb work containing lock command buffer
8038  *
8039  * Return:	0 on success, otherwise error
8040  */
8041 int smb2_lock(struct ksmbd_work *work)
8042 {
8043 	struct smb2_lock_req *req;
8044 	struct smb2_lock_rsp *rsp;
8045 	struct smb2_lock_element *lock_ele;
8046 	struct ksmbd_file *fp = NULL;
8047 	struct file_lock *flock = NULL;
8048 	struct file *filp = NULL;
8049 	int lock_count;
8050 	int flags = 0;
8051 	int cmd = 0;
8052 	int err = -EIO, i, rc = 0;
8053 	u64 lock_start, lock_length;
8054 	struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
8055 	struct ksmbd_conn *conn;
8056 	int nolock = 0;
8057 	LIST_HEAD(lock_list);
8058 	LIST_HEAD(rollback_list);
8059 	int prior_lock = 0, bkt;
8060 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
8061 
8062 	WORK_BUFFERS(work, req, rsp);
8063 
8064 	ksmbd_debug(SMB, "Received smb2 lock request\n");
8065 
8066 	if (smb2_compound_has_failed(work, &rsp->hdr))
8067 		return -EACCES;
8068 
8069 	if (work->next_smb2_rcv_hdr_off &&
8070 	    !has_file_id(req->VolatileFileId)) {
8071 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8072 			    work->compound_fid);
8073 		id = work->compound_fid;
8074 		pid = work->compound_pfid;
8075 	}
8076 
8077 	if (!has_file_id(id)) {
8078 		id = req->VolatileFileId;
8079 		pid = req->PersistentFileId;
8080 	}
8081 
8082 	fp = ksmbd_lookup_fd_slow(work, id, pid);
8083 	if (!fp) {
8084 		ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
8085 		err = -ENOENT;
8086 		goto out2;
8087 	}
8088 
8089 	filp = fp->filp;
8090 	lock_count = le16_to_cpu(req->LockCount);
8091 	lock_ele = req->locks;
8092 
8093 	ksmbd_debug(SMB, "lock count is %d\n", lock_count);
8094 	/*
8095 	 * Cap lock_count at 64. The MS-SMB2 spec defines Open.LockSequenceArray
8096 	 * as exactly 64 entries so 64 is the intended ceiling. No real workload
8097 	 * comes close to this in a single request.
8098 	 */
8099 	if (!lock_count || lock_count > 64) {
8100 		err = -EINVAL;
8101 		goto out2;
8102 	}
8103 
8104 	for (i = 0; i < lock_count; i++) {
8105 		flags = le32_to_cpu(lock_ele[i].Flags);
8106 
8107 		flock = smb_flock_init(filp);
8108 		if (!flock)
8109 			goto out;
8110 
8111 		cmd = smb2_set_flock_flags(flock, flags);
8112 
8113 		lock_start = le64_to_cpu(lock_ele[i].Offset);
8114 		lock_length = le64_to_cpu(lock_ele[i].Length);
8115 		if (lock_start > U64_MAX - lock_length) {
8116 			pr_err("Invalid lock range requested\n");
8117 			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
8118 			locks_free_lock(flock);
8119 			goto out;
8120 		}
8121 
8122 		if (lock_start > OFFSET_MAX)
8123 			flock->fl_start = OFFSET_MAX;
8124 		else
8125 			flock->fl_start = lock_start;
8126 
8127 		lock_length = le64_to_cpu(lock_ele[i].Length);
8128 		if (lock_length > OFFSET_MAX - flock->fl_start)
8129 			lock_length = OFFSET_MAX - flock->fl_start;
8130 
8131 		flock->fl_end = flock->fl_start + lock_length;
8132 
8133 		if (flock->fl_end < flock->fl_start) {
8134 			ksmbd_debug(SMB,
8135 				    "the end offset(%llx) is smaller than the start offset(%llx)\n",
8136 				    flock->fl_end, flock->fl_start);
8137 			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
8138 			locks_free_lock(flock);
8139 			goto out;
8140 		}
8141 
8142 		/* Check conflict locks in one request */
8143 		list_for_each_entry(cmp_lock, &lock_list, llist) {
8144 			if (cmp_lock->fl->fl_start <= flock->fl_start &&
8145 			    cmp_lock->fl->fl_end >= flock->fl_end) {
8146 				if (cmp_lock->fl->c.flc_type != F_UNLCK &&
8147 				    flock->c.flc_type != F_UNLCK) {
8148 					pr_err("conflict two locks in one request\n");
8149 					err = -EINVAL;
8150 					locks_free_lock(flock);
8151 					goto out;
8152 				}
8153 			}
8154 		}
8155 
8156 		smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
8157 		if (!smb_lock) {
8158 			err = -EINVAL;
8159 			locks_free_lock(flock);
8160 			goto out;
8161 		}
8162 	}
8163 
8164 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
8165 		if (smb_lock->cmd < 0) {
8166 			err = -EINVAL;
8167 			goto out;
8168 		}
8169 
8170 		if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
8171 			err = -EINVAL;
8172 			goto out;
8173 		}
8174 
8175 		if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
8176 		     smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
8177 		    (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
8178 		     !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
8179 			err = -EINVAL;
8180 			goto out;
8181 		}
8182 
8183 		prior_lock = smb_lock->flags;
8184 
8185 		if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
8186 		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
8187 			goto no_check_cl;
8188 
8189 		nolock = 1;
8190 		/* check locks in connection list */
8191 		down_read(&conn_list_lock);
8192 		hash_for_each(conn_list, bkt, conn, hlist) {
8193 			spin_lock(&conn->llist_lock);
8194 			list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
8195 				if (file_inode(cmp_lock->fl->c.flc_file) !=
8196 				    file_inode(smb_lock->fl->c.flc_file))
8197 					continue;
8198 
8199 				if (lock_is_unlock(smb_lock->fl)) {
8200 					if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file &&
8201 					    cmp_lock->start == smb_lock->start &&
8202 					    cmp_lock->end == smb_lock->end &&
8203 					    !lock_defer_pending(cmp_lock->fl)) {
8204 						nolock = 0;
8205 						list_del(&cmp_lock->flist);
8206 						list_del(&cmp_lock->clist);
8207 						cmp_lock->conn = NULL;
8208 						spin_unlock(&conn->llist_lock);
8209 						up_read(&conn_list_lock);
8210 
8211 						ksmbd_conn_put(conn);
8212 						locks_free_lock(cmp_lock->fl);
8213 						kfree(cmp_lock);
8214 						goto out_check_cl;
8215 					}
8216 					continue;
8217 				}
8218 
8219 				if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file) {
8220 					if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
8221 						continue;
8222 				} else {
8223 					if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
8224 						continue;
8225 				}
8226 
8227 				/* check zero byte lock range */
8228 				if (cmp_lock->zero_len && !smb_lock->zero_len &&
8229 				    cmp_lock->start > smb_lock->start &&
8230 				    cmp_lock->start < smb_lock->end) {
8231 					spin_unlock(&conn->llist_lock);
8232 					up_read(&conn_list_lock);
8233 					pr_err("previous lock conflict with zero byte lock range\n");
8234 					goto out;
8235 				}
8236 
8237 				if (smb_lock->zero_len && !cmp_lock->zero_len &&
8238 				    smb_lock->start > cmp_lock->start &&
8239 				    smb_lock->start < cmp_lock->end) {
8240 					spin_unlock(&conn->llist_lock);
8241 					up_read(&conn_list_lock);
8242 					pr_err("current lock conflict with zero byte lock range\n");
8243 					goto out;
8244 				}
8245 
8246 				if (((cmp_lock->start <= smb_lock->start &&
8247 				      cmp_lock->end > smb_lock->start) ||
8248 				     (cmp_lock->start < smb_lock->end &&
8249 				      cmp_lock->end >= smb_lock->end)) &&
8250 				    !cmp_lock->zero_len && !smb_lock->zero_len) {
8251 					spin_unlock(&conn->llist_lock);
8252 					up_read(&conn_list_lock);
8253 					pr_err("Not allow lock operation on exclusive lock range\n");
8254 					goto out;
8255 				}
8256 			}
8257 			spin_unlock(&conn->llist_lock);
8258 		}
8259 		up_read(&conn_list_lock);
8260 out_check_cl:
8261 		if (lock_is_unlock(smb_lock->fl) && nolock) {
8262 			pr_err("Try to unlock nolocked range\n");
8263 			rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
8264 			goto out;
8265 		}
8266 
8267 no_check_cl:
8268 		flock = smb_lock->fl;
8269 		list_del(&smb_lock->llist);
8270 
8271 		if (smb_lock->zero_len) {
8272 			err = 0;
8273 			goto skip;
8274 		}
8275 retry:
8276 		rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
8277 skip:
8278 		if (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) {
8279 			locks_free_lock(flock);
8280 			kfree(smb_lock);
8281 			if (!rc) {
8282 				ksmbd_debug(SMB, "File unlocked\n");
8283 			} else if (rc == -ENOENT) {
8284 				rsp->hdr.Status = STATUS_NOT_LOCKED;
8285 				err = rc;
8286 				goto out;
8287 			}
8288 		} else {
8289 			if (rc == FILE_LOCK_DEFERRED) {
8290 				void **argv;
8291 
8292 				ksmbd_debug(SMB,
8293 					    "would have to wait for getting lock\n");
8294 				list_add(&smb_lock->llist, &rollback_list);
8295 
8296 				argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP);
8297 				if (!argv) {
8298 					err = -ENOMEM;
8299 					goto out;
8300 				}
8301 				argv[0] = flock;
8302 
8303 				rc = setup_async_work(work,
8304 						      smb2_remove_blocked_lock,
8305 						      argv);
8306 				if (rc) {
8307 					kfree(argv);
8308 					err = -ENOMEM;
8309 					goto out;
8310 				}
8311 				spin_lock(&fp->f_lock);
8312 				list_add(&work->fp_entry, &fp->blocked_works);
8313 				spin_unlock(&fp->f_lock);
8314 
8315 				smb2_send_interim_resp(work, STATUS_PENDING);
8316 
8317 				ksmbd_vfs_posix_lock_wait(flock);
8318 
8319 				spin_lock(&fp->f_lock);
8320 				list_del(&work->fp_entry);
8321 				spin_unlock(&fp->f_lock);
8322 
8323 				list_del(&smb_lock->llist);
8324 				release_async_work(work);
8325 
8326 				if (work->state == KSMBD_WORK_ACTIVE)
8327 					goto retry;
8328 
8329 				locks_free_lock(flock);
8330 
8331 				if (work->state == KSMBD_WORK_CANCELLED) {
8332 					rsp->hdr.Status = STATUS_CANCELLED;
8333 					kfree(smb_lock);
8334 					smb2_send_interim_resp(work,
8335 							STATUS_CANCELLED);
8336 					work->send_no_response = 1;
8337 					goto out;
8338 				}
8339 
8340 				rsp->hdr.Status =
8341 					STATUS_RANGE_NOT_LOCKED;
8342 				kfree(smb_lock);
8343 				goto out2;
8344 			} else if (!rc) {
8345 				list_add(&smb_lock->llist, &rollback_list);
8346 				smb_lock->conn = ksmbd_conn_get(work->conn);
8347 				spin_lock(&work->conn->llist_lock);
8348 				list_add_tail(&smb_lock->clist,
8349 					      &work->conn->lock_list);
8350 				list_add_tail(&smb_lock->flist,
8351 					      &fp->lock_list);
8352 				spin_unlock(&work->conn->llist_lock);
8353 				ksmbd_debug(SMB, "successful in taking lock\n");
8354 			} else {
8355 				locks_free_lock(flock);
8356 				kfree(smb_lock);
8357 				err = rc;
8358 				goto out;
8359 			}
8360 		}
8361 	}
8362 
8363 	if (atomic_read(&fp->f_ci->op_count) > 1)
8364 		smb_break_all_oplock(work, fp);
8365 
8366 	rsp->StructureSize = cpu_to_le16(4);
8367 	ksmbd_debug(SMB, "successful in taking lock\n");
8368 	rsp->hdr.Status = STATUS_SUCCESS;
8369 	rsp->Reserved = 0;
8370 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
8371 	if (err)
8372 		goto out;
8373 
8374 	ksmbd_fd_put(work, fp);
8375 	return 0;
8376 
8377 out:
8378 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
8379 		locks_free_lock(smb_lock->fl);
8380 		list_del(&smb_lock->llist);
8381 		kfree(smb_lock);
8382 	}
8383 
8384 	list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
8385 		struct file_lock *rlock = NULL;
8386 
8387 		rlock = smb_flock_init(filp);
8388 		if (rlock) {
8389 			rlock->c.flc_type = F_UNLCK;
8390 			rlock->fl_start = smb_lock->start;
8391 			rlock->fl_end = smb_lock->end;
8392 
8393 			rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
8394 			if (rc)
8395 				pr_err("rollback unlock fail : %d\n", rc);
8396 		} else {
8397 			pr_err("rollback unlock alloc failed\n");
8398 		}
8399 
8400 		list_del(&smb_lock->llist);
8401 		conn = smb_lock->conn;
8402 		spin_lock(&conn->llist_lock);
8403 		if (!list_empty(&smb_lock->flist))
8404 			list_del(&smb_lock->flist);
8405 		list_del(&smb_lock->clist);
8406 		smb_lock->conn = NULL;
8407 		spin_unlock(&conn->llist_lock);
8408 		ksmbd_conn_put(conn);
8409 
8410 		locks_free_lock(smb_lock->fl);
8411 		if (rlock)
8412 			locks_free_lock(rlock);
8413 		kfree(smb_lock);
8414 	}
8415 out2:
8416 	ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
8417 
8418 	if (!rsp->hdr.Status) {
8419 		if (err == -EINVAL)
8420 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8421 		else if (err == -ENOMEM)
8422 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
8423 		else if (err == -ENOENT)
8424 			rsp->hdr.Status = STATUS_FILE_CLOSED;
8425 		else
8426 			rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
8427 	}
8428 
8429 	smb2_set_err_rsp(work);
8430 	ksmbd_fd_put(work, fp);
8431 	return err;
8432 }
8433 
8434 static int fsctl_copychunk(struct ksmbd_work *work,
8435 			   struct copychunk_ioctl_req *ci_req,
8436 			   unsigned int cnt_code,
8437 			   unsigned int input_count,
8438 			   unsigned long long volatile_id,
8439 			   unsigned long long persistent_id,
8440 			   struct smb2_ioctl_rsp *rsp)
8441 {
8442 	struct copychunk_ioctl_rsp *ci_rsp;
8443 	struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
8444 	struct srv_copychunk *chunks;
8445 	unsigned int i, chunk_count, chunk_count_written = 0;
8446 	unsigned int chunk_size_written = 0;
8447 	loff_t total_size_written = 0;
8448 	int ret = 0;
8449 
8450 	ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
8451 
8452 	rsp->VolatileFileId = volatile_id;
8453 	rsp->PersistentFileId = persistent_id;
8454 	ci_rsp->ChunksWritten =
8455 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
8456 	ci_rsp->ChunkBytesWritten =
8457 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
8458 	ci_rsp->TotalBytesWritten =
8459 		cpu_to_le32(ksmbd_server_side_copy_max_total_size());
8460 
8461 	chunk_count = le32_to_cpu(ci_req->ChunkCount);
8462 	if (chunk_count == 0)
8463 		goto out;
8464 	total_size_written = 0;
8465 
8466 	/* verify the SRV_COPYCHUNK_COPY packet */
8467 	if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
8468 	    input_count < struct_size(ci_req, Chunks, chunk_count)) {
8469 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8470 		return -EINVAL;
8471 	}
8472 
8473 	chunks = &ci_req->Chunks[0];
8474 	for (i = 0; i < chunk_count; i++) {
8475 		if (le32_to_cpu(chunks[i].Length) == 0 ||
8476 		    le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
8477 			break;
8478 		total_size_written += le32_to_cpu(chunks[i].Length);
8479 	}
8480 
8481 	if (i < chunk_count ||
8482 	    total_size_written > ksmbd_server_side_copy_max_total_size()) {
8483 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8484 		return -EINVAL;
8485 	}
8486 
8487 	src_fp = ksmbd_lookup_foreign_fd(work,
8488 					 le64_to_cpu(ci_req->SourceKeyU64[0]));
8489 	dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8490 	ret = -EINVAL;
8491 	if (!src_fp ||
8492 	    src_fp->persistent_id != le64_to_cpu(ci_req->SourceKeyU64[1])) {
8493 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
8494 		goto out;
8495 	}
8496 
8497 	if (!dst_fp) {
8498 		rsp->hdr.Status = STATUS_FILE_CLOSED;
8499 		goto out;
8500 	}
8501 
8502 	/*
8503 	 * FILE_READ_DATA should only be included in
8504 	 * the FSCTL_SRV_COPYCHUNK case
8505 	 */
8506 	if (cnt_code == FSCTL_SRV_COPYCHUNK &&
8507 	    !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
8508 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
8509 		goto out;
8510 	}
8511 
8512 	ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
8513 					 chunks, chunk_count,
8514 					 &chunk_count_written,
8515 					 &chunk_size_written,
8516 					 &total_size_written);
8517 	if (ret < 0) {
8518 		if (ret == -EACCES)
8519 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
8520 		if (ret == -EAGAIN)
8521 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
8522 		else if (ret == -EBADF)
8523 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
8524 		else if (ret == -EFBIG || ret == -ENOSPC)
8525 			rsp->hdr.Status = STATUS_DISK_FULL;
8526 		else if (ret == -EINVAL)
8527 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8528 		else if (ret == -EISDIR)
8529 			rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
8530 		else if (ret == -E2BIG)
8531 			rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
8532 		else
8533 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
8534 	}
8535 
8536 	ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
8537 	ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
8538 	ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
8539 out:
8540 	ksmbd_fd_put(work, src_fp);
8541 	ksmbd_fd_put(work, dst_fp);
8542 	return ret;
8543 }
8544 
8545 static __be32 idev_ipv4_address(struct in_device *idev)
8546 {
8547 	__be32 addr = 0;
8548 
8549 	struct in_ifaddr *ifa;
8550 
8551 	rcu_read_lock();
8552 	in_dev_for_each_ifa_rcu(ifa, idev) {
8553 		if (ifa->ifa_flags & IFA_F_SECONDARY)
8554 			continue;
8555 
8556 		addr = ifa->ifa_address;
8557 		break;
8558 	}
8559 	rcu_read_unlock();
8560 	return addr;
8561 }
8562 
8563 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
8564 					struct smb2_ioctl_rsp *rsp,
8565 					unsigned int out_buf_len)
8566 {
8567 	struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
8568 	int nbytes = 0;
8569 	struct net_device *netdev;
8570 	struct sockaddr_storage_rsp *sockaddr_storage;
8571 	unsigned int flags;
8572 	unsigned long long speed;
8573 
8574 	rtnl_lock();
8575 	for_each_netdev(&init_net, netdev) {
8576 		bool ipv4_set = false;
8577 
8578 		if (netdev->type == ARPHRD_LOOPBACK)
8579 			continue;
8580 
8581 		if (!ksmbd_find_netdev_name_iface_list(netdev->name))
8582 			continue;
8583 
8584 		flags = netif_get_flags(netdev);
8585 		if (!(flags & IFF_RUNNING))
8586 			continue;
8587 ipv6_retry:
8588 		if (out_buf_len <
8589 		    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
8590 			rtnl_unlock();
8591 			return -ENOSPC;
8592 		}
8593 
8594 		nii_rsp = (struct network_interface_info_ioctl_rsp *)
8595 				&rsp->Buffer[nbytes];
8596 		nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
8597 
8598 		nii_rsp->Capability = 0;
8599 		if (netdev->real_num_tx_queues > 1)
8600 			nii_rsp->Capability |= RSS_CAPABLE;
8601 		if (ksmbd_rdma_capable_netdev(netdev))
8602 			nii_rsp->Capability |= RDMA_CAPABLE;
8603 
8604 		nii_rsp->Next = cpu_to_le32(152);
8605 		nii_rsp->Reserved = 0;
8606 
8607 		if (netdev->ethtool_ops->get_link_ksettings) {
8608 			struct ethtool_link_ksettings cmd;
8609 
8610 			netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
8611 			speed = cmd.base.speed;
8612 		} else {
8613 			ksmbd_debug(SMB, "%s %s\n", netdev->name,
8614 				    "speed is unknown, defaulting to 1Gb/sec");
8615 			speed = SPEED_1000;
8616 		}
8617 
8618 		speed *= 1000000;
8619 		nii_rsp->LinkSpeed = cpu_to_le64(speed);
8620 
8621 		sockaddr_storage = (struct sockaddr_storage_rsp *)
8622 					nii_rsp->SockAddr_Storage;
8623 		memset(sockaddr_storage, 0, 128);
8624 
8625 		if (!ipv4_set) {
8626 			struct in_device *idev;
8627 
8628 			sockaddr_storage->Family = INTERNETWORK;
8629 			sockaddr_storage->addr4.Port = 0;
8630 
8631 			idev = __in_dev_get_rtnl(netdev);
8632 			if (!idev)
8633 				continue;
8634 			sockaddr_storage->addr4.IPv4Address =
8635 						idev_ipv4_address(idev);
8636 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
8637 			ipv4_set = true;
8638 			goto ipv6_retry;
8639 		} else {
8640 			struct inet6_dev *idev6;
8641 			struct inet6_ifaddr *ifa;
8642 			__u8 *ipv6_addr = sockaddr_storage->addr6.IPv6Address;
8643 
8644 			sockaddr_storage->Family = INTERNETWORKV6;
8645 			sockaddr_storage->addr6.Port = 0;
8646 			sockaddr_storage->addr6.FlowInfo = 0;
8647 
8648 			idev6 = __in6_dev_get(netdev);
8649 			if (!idev6)
8650 				continue;
8651 
8652 			list_for_each_entry(ifa, &idev6->addr_list, if_list) {
8653 				if (ifa->flags & (IFA_F_TENTATIVE |
8654 							IFA_F_DEPRECATED))
8655 					continue;
8656 				memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
8657 				break;
8658 			}
8659 			sockaddr_storage->addr6.ScopeId = 0;
8660 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
8661 		}
8662 	}
8663 	rtnl_unlock();
8664 
8665 	/* zero if this is last one */
8666 	if (nii_rsp)
8667 		nii_rsp->Next = 0;
8668 
8669 	rsp->PersistentFileId = SMB2_NO_FID;
8670 	rsp->VolatileFileId = SMB2_NO_FID;
8671 	return nbytes;
8672 }
8673 
8674 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
8675 					 struct validate_negotiate_info_req *neg_req,
8676 					 struct validate_negotiate_info_rsp *neg_rsp,
8677 					 unsigned int in_buf_len)
8678 {
8679 	int ret = 0;
8680 	int dialect;
8681 
8682 	if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
8683 			le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
8684 		return -EINVAL;
8685 
8686 	dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
8687 					     neg_req->DialectCount);
8688 	if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
8689 		ret = -EINVAL;
8690 		goto err_out;
8691 	}
8692 
8693 	if (memcmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
8694 		ret = -EINVAL;
8695 		goto err_out;
8696 	}
8697 
8698 	if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
8699 		ret = -EINVAL;
8700 		goto err_out;
8701 	}
8702 
8703 	if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
8704 		ret = -EINVAL;
8705 		goto err_out;
8706 	}
8707 
8708 	neg_rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
8709 	memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
8710 	neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
8711 	neg_rsp->Dialect = cpu_to_le16(conn->dialect);
8712 err_out:
8713 	return ret;
8714 }
8715 
8716 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
8717 					struct file_allocated_range_buffer *qar_req,
8718 					struct file_allocated_range_buffer *qar_rsp,
8719 					unsigned int in_count, unsigned int *out_count)
8720 {
8721 	struct ksmbd_file *fp;
8722 	loff_t start, length;
8723 	int ret = 0;
8724 
8725 	*out_count = 0;
8726 	if (in_count == 0)
8727 		return -EINVAL;
8728 
8729 	start = le64_to_cpu(qar_req->file_offset);
8730 	length = le64_to_cpu(qar_req->length);
8731 
8732 	if (start < 0 || length < 0)
8733 		return -EINVAL;
8734 
8735 	fp = ksmbd_lookup_fd_fast(work, id);
8736 	if (!fp)
8737 		return -ENOENT;
8738 
8739 	ret = ksmbd_vfs_fqar_lseek(fp, start, length,
8740 				   qar_rsp, in_count, out_count);
8741 	if (ret && ret != -E2BIG)
8742 		*out_count = 0;
8743 
8744 	ksmbd_fd_put(work, fp);
8745 	return ret;
8746 }
8747 
8748 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
8749 				 unsigned int out_buf_len,
8750 				 struct smb2_ioctl_req *req,
8751 				 struct smb2_ioctl_rsp *rsp)
8752 {
8753 	struct ksmbd_rpc_command *rpc_resp;
8754 	char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
8755 	int nbytes = 0;
8756 
8757 	rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
8758 				   le32_to_cpu(req->InputCount));
8759 	if (rpc_resp) {
8760 		if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
8761 			/*
8762 			 * set STATUS_SOME_NOT_MAPPED response
8763 			 * for unknown domain sid.
8764 			 */
8765 			rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
8766 		} else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
8767 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8768 			goto out;
8769 		} else if (rpc_resp->flags != KSMBD_RPC_OK) {
8770 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8771 			goto out;
8772 		}
8773 
8774 		nbytes = rpc_resp->payload_sz;
8775 		if (rpc_resp->payload_sz > out_buf_len) {
8776 			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8777 			nbytes = out_buf_len;
8778 		}
8779 
8780 		if (!rpc_resp->payload_sz) {
8781 			rsp->hdr.Status =
8782 				STATUS_UNEXPECTED_IO_ERROR;
8783 			goto out;
8784 		}
8785 
8786 		memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
8787 	}
8788 out:
8789 	kvfree(rpc_resp);
8790 	return nbytes;
8791 }
8792 
8793 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
8794 				   struct file_sparse *sparse)
8795 {
8796 	struct ksmbd_file *fp;
8797 	struct mnt_idmap *idmap;
8798 	int ret = 0;
8799 	__le32 old_fattr;
8800 
8801 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8802 		ksmbd_debug(SMB, "User does not have write permission\n");
8803 		return -EACCES;
8804 	}
8805 
8806 	fp = ksmbd_lookup_fd_fast(work, id);
8807 	if (!fp)
8808 		return -ENOENT;
8809 
8810 	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_WRITE_ATTRIBUTES_LE))) {
8811 		ret = -EACCES;
8812 		goto out;
8813 	}
8814 
8815 	idmap = file_mnt_idmap(fp->filp);
8816 
8817 	old_fattr = fp->f_ci->m_fattr;
8818 	if (sparse->SetSparse)
8819 		fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
8820 	else
8821 		fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
8822 
8823 	if (fp->f_ci->m_fattr != old_fattr &&
8824 	    test_share_config_flag(work->tcon->share_conf,
8825 				   KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
8826 		const struct cred *saved_cred;
8827 		struct xattr_dos_attrib da;
8828 
8829 		ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
8830 						     fp->filp->f_path.dentry, &da);
8831 		if (ret <= 0)
8832 			goto out;
8833 
8834 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
8835 		saved_cred = override_creds(fp->filp->f_cred);
8836 		ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
8837 						     &fp->filp->f_path,
8838 						     &da, true);
8839 		revert_creds(saved_cred);
8840 		if (ret)
8841 			fp->f_ci->m_fattr = old_fattr;
8842 	}
8843 
8844 out:
8845 	ksmbd_fd_put(work, fp);
8846 	return ret;
8847 }
8848 
8849 static int fsctl_request_resume_key(struct ksmbd_work *work,
8850 				    struct smb2_ioctl_req *req,
8851 				    struct resume_key_ioctl_rsp *key_rsp)
8852 {
8853 	struct ksmbd_file *fp;
8854 
8855 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
8856 	if (!fp)
8857 		return -ENOENT;
8858 
8859 	memset(key_rsp, 0, sizeof(*key_rsp));
8860 	key_rsp->ResumeKeyU64[0] = req->VolatileFileId;
8861 	key_rsp->ResumeKeyU64[1] = req->PersistentFileId;
8862 	ksmbd_fd_put(work, fp);
8863 
8864 	return 0;
8865 }
8866 
8867 /**
8868  * smb2_ioctl() - handler for smb2 ioctl command
8869  * @work:	smb work containing ioctl command buffer
8870  *
8871  * Return:	0 on success, otherwise error
8872  */
8873 int smb2_ioctl(struct ksmbd_work *work)
8874 {
8875 	struct smb2_ioctl_req *req;
8876 	struct smb2_ioctl_rsp *rsp;
8877 	unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
8878 	u64 id = KSMBD_NO_FID;
8879 	struct ksmbd_conn *conn = work->conn;
8880 	int ret = 0;
8881 	char *buffer;
8882 
8883 	ksmbd_debug(SMB, "Received smb2 ioctl request\n");
8884 
8885 	if (work->next_smb2_rcv_hdr_off) {
8886 		req = ksmbd_req_buf_next(work);
8887 		rsp = ksmbd_resp_buf_next(work);
8888 		if (smb2_compound_has_failed(work, &rsp->hdr))
8889 			return -EACCES;
8890 		if (!has_file_id(req->VolatileFileId)) {
8891 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8892 				    work->compound_fid);
8893 			id = work->compound_fid;
8894 		}
8895 	} else {
8896 		req = smb_get_msg(work->request_buf);
8897 		rsp = smb_get_msg(work->response_buf);
8898 	}
8899 
8900 	if (!has_file_id(id))
8901 		id = req->VolatileFileId;
8902 
8903 	if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
8904 		ret = -EOPNOTSUPP;
8905 		goto out;
8906 	}
8907 
8908 	buffer = (char *)req + le32_to_cpu(req->InputOffset);
8909 
8910 	cnt_code = le32_to_cpu(req->CtlCode);
8911 	ret = smb2_calc_max_out_buf_len(work,
8912 			offsetof(struct smb2_ioctl_rsp, Buffer),
8913 			le32_to_cpu(req->MaxOutputResponse));
8914 	if (ret < 0) {
8915 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8916 		goto out;
8917 	}
8918 	out_buf_len = (unsigned int)ret;
8919 	in_buf_len = le32_to_cpu(req->InputCount);
8920 
8921 	switch (cnt_code) {
8922 	case FSCTL_DFS_GET_REFERRALS:
8923 	case FSCTL_DFS_GET_REFERRALS_EX:
8924 		/* Not support DFS yet */
8925 		ret = -EOPNOTSUPP;
8926 		rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
8927 		goto out2;
8928 	case FSCTL_GET_COMPRESSION: {
8929 		struct compress_ioctl *cmpr_rsp;
8930 		struct ksmbd_file *fp;
8931 		u16 fmt;
8932 
8933 		if (out_buf_len < sizeof(struct compress_ioctl)) {
8934 			ret = -EINVAL;
8935 			goto out;
8936 		}
8937 
8938 		fp = ksmbd_lookup_fd_fast(work, id);
8939 		if (!fp) {
8940 			ret = -ENOENT;
8941 			goto out;
8942 		}
8943 
8944 		ret = ksmbd_vfs_get_compression(fp, &fmt);
8945 		ksmbd_fd_put(work, fp);
8946 		if (ret < 0)
8947 			goto out;
8948 
8949 		cmpr_rsp = (struct compress_ioctl *)&rsp->Buffer[0];
8950 		cmpr_rsp->CompressionState = cpu_to_le16(fmt);
8951 		nbytes = sizeof(struct compress_ioctl);
8952 		rsp->PersistentFileId = req->PersistentFileId;
8953 		rsp->VolatileFileId = req->VolatileFileId;
8954 		break;
8955 	}
8956 	case FSCTL_SET_COMPRESSION: {
8957 		struct compress_ioctl *cmpr_req;
8958 		struct ksmbd_file *fp;
8959 
8960 		if (in_buf_len < sizeof(struct compress_ioctl)) {
8961 			ret = -EINVAL;
8962 			goto out;
8963 		}
8964 
8965 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8966 			ksmbd_debug(SMB, "User does not have write permission\n");
8967 			ret = -EACCES;
8968 			goto out;
8969 		}
8970 
8971 		cmpr_req = (struct compress_ioctl *)buffer;
8972 		fp = ksmbd_lookup_fd_fast(work, id);
8973 		if (!fp) {
8974 			ret = -ENOENT;
8975 			goto out;
8976 		}
8977 
8978 		ret = ksmbd_vfs_set_compression(work, fp, le16_to_cpu(cmpr_req->CompressionState));
8979 		ksmbd_fd_put(work, fp);
8980 		if (ret)
8981 			goto out;
8982 		break;
8983 	}
8984 	case FSCTL_CREATE_OR_GET_OBJECT_ID:
8985 	{
8986 		struct file_object_buf_type1_ioctl_rsp *obj_buf;
8987 		struct ksmbd_file *fp;
8988 
8989 		fp = ksmbd_lookup_fd_fast(work, id);
8990 		if (!fp) {
8991 			ret = -EBADF;
8992 			rsp->hdr.Status = STATUS_FILE_CLOSED;
8993 			goto out2;
8994 		}
8995 		ksmbd_fd_put(work, fp);
8996 
8997 		nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
8998 		obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
8999 			&rsp->Buffer[0];
9000 
9001 		/*
9002 		 * TODO: This is dummy implementation to pass smbtorture
9003 		 * Need to check correct response later
9004 		 */
9005 		memset(obj_buf->ObjectId, 0x0, 16);
9006 		memset(obj_buf->BirthVolumeId, 0x0, 16);
9007 		memset(obj_buf->BirthObjectId, 0x0, 16);
9008 		memset(obj_buf->DomainId, 0x0, 16);
9009 
9010 		break;
9011 	}
9012 	case FSCTL_PIPE_TRANSCEIVE:
9013 		out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
9014 		nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
9015 		break;
9016 	case FSCTL_VALIDATE_NEGOTIATE_INFO:
9017 		if (conn->dialect < SMB30_PROT_ID) {
9018 			ret = -EOPNOTSUPP;
9019 			goto out;
9020 		}
9021 
9022 		if (in_buf_len < offsetof(struct validate_negotiate_info_req,
9023 					  Dialects)) {
9024 			ret = -EINVAL;
9025 			goto out;
9026 		}
9027 
9028 		if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
9029 			ret = -EINVAL;
9030 			goto out;
9031 		}
9032 
9033 		ret = fsctl_validate_negotiate_info(conn,
9034 			(struct validate_negotiate_info_req *)buffer,
9035 			(struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
9036 			in_buf_len);
9037 		if (ret < 0)
9038 			goto out;
9039 
9040 		nbytes = sizeof(struct validate_negotiate_info_rsp);
9041 		rsp->PersistentFileId = SMB2_NO_FID;
9042 		rsp->VolatileFileId = SMB2_NO_FID;
9043 		break;
9044 	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
9045 		ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
9046 		if (ret < 0)
9047 			goto out;
9048 		nbytes = ret;
9049 		break;
9050 	case FSCTL_SRV_REQUEST_RESUME_KEY:
9051 		if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
9052 			ret = -EINVAL;
9053 			goto out;
9054 		}
9055 
9056 		ret = fsctl_request_resume_key(work, req,
9057 					       (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
9058 		if (ret < 0)
9059 			goto out;
9060 		rsp->PersistentFileId = req->PersistentFileId;
9061 		rsp->VolatileFileId = req->VolatileFileId;
9062 		nbytes = sizeof(struct resume_key_ioctl_rsp);
9063 		break;
9064 	case FSCTL_SRV_COPYCHUNK:
9065 	case FSCTL_SRV_COPYCHUNK_WRITE:
9066 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
9067 			ksmbd_debug(SMB,
9068 				    "User does not have write permission\n");
9069 			ret = -EACCES;
9070 			goto out;
9071 		}
9072 
9073 		if (in_buf_len <= sizeof(struct copychunk_ioctl_req)) {
9074 			ret = -EINVAL;
9075 			goto out;
9076 		}
9077 
9078 		if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
9079 			ret = -EINVAL;
9080 			goto out;
9081 		}
9082 
9083 		nbytes = sizeof(struct copychunk_ioctl_rsp);
9084 		rsp->VolatileFileId = req->VolatileFileId;
9085 		rsp->PersistentFileId = req->PersistentFileId;
9086 		fsctl_copychunk(work,
9087 				(struct copychunk_ioctl_req *)buffer,
9088 				le32_to_cpu(req->CtlCode),
9089 				le32_to_cpu(req->InputCount),
9090 				req->VolatileFileId,
9091 				req->PersistentFileId,
9092 				rsp);
9093 		break;
9094 	case FSCTL_SET_SPARSE:
9095 		if (in_buf_len < sizeof(struct file_sparse)) {
9096 			ret = -EINVAL;
9097 			goto out;
9098 		}
9099 
9100 		ret = fsctl_set_sparse(work, id, (struct file_sparse *)buffer);
9101 		if (ret < 0)
9102 			goto out;
9103 		break;
9104 	case FSCTL_SET_ZERO_DATA:
9105 	{
9106 		struct file_zero_data_information *zero_data;
9107 		struct ksmbd_file *fp;
9108 		loff_t off, len, bfz;
9109 
9110 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
9111 			ksmbd_debug(SMB,
9112 				    "User does not have write permission\n");
9113 			ret = -EACCES;
9114 			goto out;
9115 		}
9116 
9117 		if (in_buf_len < sizeof(struct file_zero_data_information)) {
9118 			ret = -EINVAL;
9119 			goto out;
9120 		}
9121 
9122 		zero_data =
9123 			(struct file_zero_data_information *)buffer;
9124 
9125 		off = le64_to_cpu(zero_data->FileOffset);
9126 		bfz = le64_to_cpu(zero_data->BeyondFinalZero);
9127 		if (off < 0 || bfz < 0 || off > bfz) {
9128 			ret = -EINVAL;
9129 			goto out;
9130 		}
9131 
9132 		len = bfz - off;
9133 		if (len) {
9134 			fp = ksmbd_lookup_fd_fast(work, id);
9135 			if (!fp) {
9136 				ret = -ENOENT;
9137 				goto out;
9138 			}
9139 
9140 			if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
9141 				ksmbd_fd_put(work, fp);
9142 				ret = -EACCES;
9143 				goto out;
9144 			}
9145 
9146 			ret = ksmbd_vfs_zero_data(work, fp, off, len);
9147 			ksmbd_fd_put(work, fp);
9148 			if (ret < 0)
9149 				goto out;
9150 		}
9151 		break;
9152 	}
9153 	case FSCTL_QUERY_ALLOCATED_RANGES:
9154 		if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
9155 			ret = -EINVAL;
9156 			goto out;
9157 		}
9158 
9159 		ret = fsctl_query_allocated_ranges(work, id,
9160 			(struct file_allocated_range_buffer *)buffer,
9161 			(struct file_allocated_range_buffer *)&rsp->Buffer[0],
9162 			out_buf_len /
9163 			sizeof(struct file_allocated_range_buffer), &nbytes);
9164 		if (ret == -E2BIG) {
9165 			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
9166 		} else if (ret < 0) {
9167 			nbytes = 0;
9168 			goto out;
9169 		}
9170 
9171 		nbytes *= sizeof(struct file_allocated_range_buffer);
9172 		break;
9173 	case FSCTL_GET_REPARSE_POINT:
9174 	{
9175 		struct reparse_data_buffer *reparse_ptr;
9176 		struct ksmbd_file *fp;
9177 
9178 		reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
9179 		fp = ksmbd_lookup_fd_fast(work, id);
9180 		if (!fp) {
9181 			pr_err("not found fp!!\n");
9182 			ret = -ENOENT;
9183 			goto out;
9184 		}
9185 
9186 		reparse_ptr->ReparseTag =
9187 			smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
9188 		reparse_ptr->ReparseDataLength = 0;
9189 		ksmbd_fd_put(work, fp);
9190 		nbytes = sizeof(struct reparse_data_buffer);
9191 		break;
9192 	}
9193 	case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
9194 	{
9195 		struct ksmbd_file *fp_in, *fp_out = NULL;
9196 		struct duplicate_extents_to_file *dup_ext;
9197 		loff_t src_off, dst_off, length, cloned;
9198 
9199 		if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
9200 			ret = -EINVAL;
9201 			goto out;
9202 		}
9203 
9204 		dup_ext = (struct duplicate_extents_to_file *)buffer;
9205 
9206 		fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
9207 					     dup_ext->PersistentFileHandle);
9208 		if (!fp_in) {
9209 			pr_err("not found file handle in duplicate extent to file\n");
9210 			ret = -ENOENT;
9211 			goto out;
9212 		}
9213 
9214 		fp_out = ksmbd_lookup_fd_fast(work, id);
9215 		if (!fp_out) {
9216 			pr_err("not found fp\n");
9217 			ret = -ENOENT;
9218 			goto dup_ext_out;
9219 		}
9220 
9221 		if (!test_tree_conn_flag(work->tcon,
9222 					 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
9223 			ret = -EACCES;
9224 			goto dup_ext_out;
9225 		}
9226 
9227 		if (!(fp_out->daccess & FILE_WRITE_DATA_LE)) {
9228 			ret = -EACCES;
9229 			goto dup_ext_out;
9230 		}
9231 		if (!(fp_in->daccess & FILE_READ_DATA_LE)) {
9232 			ret = -EACCES;
9233 			goto dup_ext_out;
9234 		}
9235 
9236 		src_off = le64_to_cpu(dup_ext->SourceFileOffset);
9237 		dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
9238 		length = le64_to_cpu(dup_ext->ByteCount);
9239 		/*
9240 		 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
9241 		 * should fall back to vfs_copy_file_range().  This could be
9242 		 * beneficial when re-exporting nfs/smb mount, but note that
9243 		 * this can result in partial copy that returns an error status.
9244 		 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
9245 		 * fall back to vfs_copy_file_range(), should be avoided when
9246 		 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
9247 		 */
9248 		cloned = vfs_clone_file_range(fp_in->filp, src_off,
9249 					      fp_out->filp, dst_off, length, 0);
9250 		if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
9251 			ret = -EOPNOTSUPP;
9252 			goto dup_ext_out;
9253 		} else if (cloned != length) {
9254 			cloned = vfs_copy_file_range(fp_in->filp, src_off,
9255 						     fp_out->filp, dst_off,
9256 						     length, 0);
9257 			if (cloned != length) {
9258 				if (cloned < 0)
9259 					ret = cloned;
9260 				else
9261 					ret = -EINVAL;
9262 			}
9263 		}
9264 
9265 dup_ext_out:
9266 		ksmbd_fd_put(work, fp_in);
9267 		ksmbd_fd_put(work, fp_out);
9268 		if (ret < 0)
9269 			goto out;
9270 		break;
9271 	}
9272 	default:
9273 		ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
9274 			    cnt_code);
9275 		ret = -EOPNOTSUPP;
9276 		goto out;
9277 	}
9278 
9279 	rsp->CtlCode = cpu_to_le32(cnt_code);
9280 	rsp->InputCount = cpu_to_le32(0);
9281 	rsp->InputOffset = cpu_to_le32(112);
9282 	rsp->OutputOffset = cpu_to_le32(112);
9283 	rsp->OutputCount = cpu_to_le32(nbytes);
9284 	rsp->StructureSize = cpu_to_le16(49);
9285 	rsp->Reserved = cpu_to_le16(0);
9286 	rsp->Flags = cpu_to_le32(0);
9287 	rsp->Reserved2 = cpu_to_le32(0);
9288 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
9289 	if (!ret)
9290 		return ret;
9291 
9292 out:
9293 	if (ret == -EACCES)
9294 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
9295 	else if (ret == -ENOENT)
9296 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
9297 	else if (ret == -EOPNOTSUPP)
9298 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
9299 	else if (ret == -ENOSPC)
9300 		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
9301 	else if (ret < 0 || rsp->hdr.Status == 0)
9302 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
9303 
9304 out2:
9305 	smb2_set_err_rsp(work);
9306 	return ret;
9307 }
9308 
9309 /**
9310  * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
9311  * @work:	smb work containing oplock break command buffer
9312  *
9313  * Return:	0
9314  */
9315 static void smb20_oplock_break_ack(struct ksmbd_work *work)
9316 {
9317 	struct smb2_oplock_break *req;
9318 	struct smb2_oplock_break *rsp;
9319 	struct ksmbd_file *fp;
9320 	struct oplock_info *opinfo = NULL;
9321 	__le32 status = STATUS_SUCCESS;
9322 	int ret;
9323 	u64 volatile_id, persistent_id;
9324 	char req_oplevel = 0, rsp_oplevel = 0;
9325 
9326 	WORK_BUFFERS(work, req, rsp);
9327 
9328 	volatile_id = req->VolatileFid;
9329 	persistent_id = req->PersistentFid;
9330 	req_oplevel = req->OplockLevel;
9331 	ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
9332 		    volatile_id, persistent_id, req_oplevel);
9333 
9334 	fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
9335 	if (!fp) {
9336 		rsp->hdr.Status = STATUS_FILE_CLOSED;
9337 		smb2_set_err_rsp(work);
9338 		return;
9339 	}
9340 
9341 	opinfo = opinfo_get(fp);
9342 	if (!opinfo) {
9343 		pr_err("unexpected null oplock_info\n");
9344 		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
9345 		smb2_set_err_rsp(work);
9346 		ksmbd_fd_put(work, fp);
9347 		return;
9348 	}
9349 
9350 	if (opinfo->op_state != OPLOCK_ACK_WAIT) {
9351 		ksmbd_debug(SMB, "unexpected oplock state 0x%x\n",
9352 			    opinfo->op_state);
9353 		if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE)
9354 			status = STATUS_INVALID_OPLOCK_PROTOCOL;
9355 		else
9356 			status = STATUS_INVALID_DEVICE_STATE;
9357 		goto err_out;
9358 	}
9359 
9360 	if (req_oplevel == SMB2_OPLOCK_LEVEL_LEASE) {
9361 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
9362 		status = STATUS_INVALID_PARAMETER;
9363 		goto err_out;
9364 	}
9365 
9366 	if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
9367 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
9368 		goto err_out;
9369 	}
9370 
9371 	if (opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE &&
9372 	    req_oplevel != SMB2_OPLOCK_LEVEL_II &&
9373 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
9374 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
9375 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
9376 		goto err_out;
9377 	}
9378 
9379 	if (opinfo->level == SMB2_OPLOCK_LEVEL_BATCH &&
9380 	    req_oplevel != SMB2_OPLOCK_LEVEL_II &&
9381 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE &&
9382 	    req_oplevel != SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
9383 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
9384 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
9385 		goto err_out;
9386 	}
9387 
9388 	if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
9389 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
9390 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
9391 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
9392 		goto err_out;
9393 	}
9394 
9395 	if (req_oplevel == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
9396 		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
9397 	else
9398 		rsp_oplevel = req_oplevel;
9399 
9400 	opinfo->level = rsp_oplevel;
9401 
9402 	rsp->StructureSize = cpu_to_le16(24);
9403 	rsp->OplockLevel = rsp_oplevel;
9404 	rsp->Reserved = 0;
9405 	rsp->Reserved2 = 0;
9406 	rsp->VolatileFid = volatile_id;
9407 	rsp->PersistentFid = persistent_id;
9408 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
9409 	if (ret)
9410 		ksmbd_debug(SMB, "failed to pin oplock break response: %d\n",
9411 			    ret);
9412 	goto out;
9413 
9414 err_out:
9415 	rsp->hdr.Status = status;
9416 	smb2_set_err_rsp(work);
9417 
9418 out:
9419 	opinfo->op_state = OPLOCK_STATE_NONE;
9420 	wake_up_interruptible_all(&opinfo->oplock_q);
9421 	opinfo_put(opinfo);
9422 	ksmbd_fd_put(work, fp);
9423 }
9424 
9425 static bool smb2_lease_state_valid(__le32 state)
9426 {
9427 	return !(state & ~(SMB2_LEASE_READ_CACHING_LE |
9428 			   SMB2_LEASE_HANDLE_CACHING_LE |
9429 			   SMB2_LEASE_WRITE_CACHING_LE));
9430 }
9431 
9432 static int check_lease_state(struct lease *lease, __le32 req_state)
9433 {
9434 	if (smb2_lease_state_valid(req_state) &&
9435 	    !(req_state & ~lease->new_state))
9436 		return 0;
9437 
9438 	return 1;
9439 }
9440 
9441 /**
9442  * smb21_lease_break_ack() - handler for smb2.1 lease break command
9443  * @work:	smb work containing lease break command buffer
9444  *
9445  * Return:	0
9446  */
9447 static void smb21_lease_break_ack(struct ksmbd_work *work)
9448 {
9449 	struct ksmbd_conn *conn = work->conn;
9450 	struct smb2_lease_ack *req;
9451 	struct smb2_lease_ack *rsp;
9452 	struct oplock_info *opinfo;
9453 	int ret = 0;
9454 	__le32 lease_state;
9455 	struct lease *lease;
9456 
9457 	WORK_BUFFERS(work, req, rsp);
9458 
9459 	ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
9460 		    le32_to_cpu(req->LeaseState));
9461 	opinfo = lookup_lease_in_table(conn, req->LeaseKey);
9462 	if (!opinfo) {
9463 		ksmbd_debug(OPLOCK, "file not opened\n");
9464 		smb2_set_err_rsp(work);
9465 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
9466 		return;
9467 	}
9468 	lease = opinfo->o_lease;
9469 
9470 	if (opinfo->op_state == OPLOCK_STATE_NONE) {
9471 		pr_err("unexpected lease break state 0x%x\n",
9472 		       opinfo->op_state);
9473 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
9474 		goto err_out;
9475 	}
9476 
9477 	if (!atomic_read(&opinfo->breaking_cnt)) {
9478 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
9479 		goto err_out;
9480 	}
9481 
9482 	if (check_lease_state(lease, req->LeaseState)) {
9483 		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
9484 		ksmbd_debug(OPLOCK,
9485 			    "req lease state: 0x%x, expected state: 0x%x\n",
9486 			    req->LeaseState, lease->new_state);
9487 		goto err_out;
9488 	}
9489 
9490 	lease_state = req->LeaseState;
9491 	lease->state = lease_state;
9492 	lease->new_state = SMB2_LEASE_NONE_LE;
9493 	lease_update_oplock_levels(lease);
9494 
9495 	rsp->StructureSize = cpu_to_le16(36);
9496 	rsp->Reserved = 0;
9497 	rsp->Flags = 0;
9498 	memcpy(rsp->LeaseKey, req->LeaseKey, 16);
9499 	rsp->LeaseState = lease_state;
9500 	rsp->LeaseDuration = 0;
9501 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
9502 	if (ret)
9503 		goto err_out;
9504 
9505 	opinfo->op_state = OPLOCK_STATE_NONE;
9506 	wake_up_interruptible_all(&opinfo->oplock_q);
9507 	atomic_dec(&opinfo->breaking_cnt);
9508 	wake_up_interruptible_all(&opinfo->oplock_brk);
9509 	opinfo_put(opinfo);
9510 	return;
9511 
9512 err_out:
9513 	smb2_set_err_rsp(work);
9514 	opinfo_put(opinfo);
9515 	return;
9516 }
9517 
9518 /**
9519  * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
9520  * @work:	smb work containing oplock/lease break command buffer
9521  *
9522  * Return:	0 on success, otherwise error
9523  */
9524 int smb2_oplock_break(struct ksmbd_work *work)
9525 {
9526 	struct smb2_oplock_break *req;
9527 	struct smb2_oplock_break *rsp;
9528 
9529 	ksmbd_debug(SMB, "Received smb2 oplock break acknowledgment request\n");
9530 
9531 	WORK_BUFFERS(work, req, rsp);
9532 
9533 	switch (le16_to_cpu(req->StructureSize)) {
9534 	case OP_BREAK_STRUCT_SIZE_20:
9535 		smb20_oplock_break_ack(work);
9536 		break;
9537 	case OP_BREAK_STRUCT_SIZE_21:
9538 		smb21_lease_break_ack(work);
9539 		break;
9540 	default:
9541 		ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
9542 			    le16_to_cpu(req->StructureSize));
9543 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
9544 		smb2_set_err_rsp(work);
9545 		return -EINVAL;
9546 	}
9547 
9548 	return 0;
9549 }
9550 
9551 /**
9552  * smb2_notify() - handler for smb2 notify request
9553  * @work:   smb work containing notify command buffer
9554  *
9555  * Return:      0 on success, otherwise error
9556  */
9557 int smb2_notify(struct ksmbd_work *work)
9558 {
9559 	struct smb2_change_notify_req *req;
9560 	struct smb2_change_notify_rsp *rsp;
9561 
9562 	ksmbd_debug(SMB, "Received smb2 notify\n");
9563 
9564 	WORK_BUFFERS(work, req, rsp);
9565 
9566 	if (smb2_compound_has_failed(work, &rsp->hdr))
9567 		return -EACCES;
9568 
9569 	if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
9570 		rsp->hdr.Status = STATUS_INTERNAL_ERROR;
9571 		smb2_set_err_rsp(work);
9572 		return -EIO;
9573 	}
9574 
9575 	smb2_set_err_rsp(work);
9576 	rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
9577 	return -EOPNOTSUPP;
9578 }
9579 
9580 /**
9581  * smb2_is_sign_req() - handler for checking packet signing status
9582  * @work:	smb work containing notify command buffer
9583  * @command:	SMB2 command id
9584  *
9585  * Return:	true if packed is signed, false otherwise
9586  */
9587 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
9588 {
9589 	struct smb2_hdr *rcv_hdr2 = smb_get_msg(work->request_buf);
9590 
9591 	if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
9592 	    command != SMB2_NEGOTIATE_HE)
9593 		return true;
9594 
9595 	return false;
9596 }
9597 
9598 /**
9599  * smb2_check_sign_req() - handler for req packet sign processing
9600  * @work:   smb work containing notify command buffer
9601  *
9602  * Return:	1 on success, 0 otherwise
9603  */
9604 int smb2_check_sign_req(struct ksmbd_work *work)
9605 {
9606 	struct smb2_hdr *hdr;
9607 	char signature_req[SMB2_SIGNATURE_SIZE];
9608 	char signature[SMB2_HMACSHA256_SIZE];
9609 	struct kvec iov[1];
9610 	size_t len;
9611 
9612 	hdr = smb_get_msg(work->request_buf);
9613 	if (work->next_smb2_rcv_hdr_off)
9614 		hdr = ksmbd_req_buf_next(work);
9615 
9616 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
9617 		len = get_rfc1002_len(work->request_buf);
9618 	else if (hdr->NextCommand)
9619 		len = le32_to_cpu(hdr->NextCommand);
9620 	else
9621 		len = get_rfc1002_len(work->request_buf) -
9622 			work->next_smb2_rcv_hdr_off;
9623 
9624 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
9625 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9626 
9627 	iov[0].iov_base = (char *)&hdr->ProtocolId;
9628 	iov[0].iov_len = len;
9629 
9630 	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
9631 			    signature);
9632 
9633 	if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
9634 		pr_err("bad smb2 signature\n");
9635 		return 0;
9636 	}
9637 
9638 	return 1;
9639 }
9640 
9641 /**
9642  * smb2_set_sign_rsp() - handler for rsp packet sign processing
9643  * @work:   smb work containing notify command buffer
9644  *
9645  */
9646 void smb2_set_sign_rsp(struct ksmbd_work *work)
9647 {
9648 	struct smb2_hdr *hdr;
9649 	char signature[SMB2_HMACSHA256_SIZE];
9650 	struct kvec *iov;
9651 	int n_vec = 1;
9652 
9653 	hdr = ksmbd_resp_buf_curr(work);
9654 	hdr->Flags |= SMB2_FLAGS_SIGNED;
9655 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9656 
9657 	if (hdr->Command == SMB2_READ) {
9658 		iov = &work->iov[work->iov_idx - 1];
9659 		n_vec++;
9660 	} else {
9661 		iov = &work->iov[work->iov_idx];
9662 	}
9663 
9664 	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
9665 			    signature);
9666 	memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
9667 }
9668 
9669 /**
9670  * smb3_check_sign_req() - handler for req packet sign processing
9671  * @work:   smb work containing notify command buffer
9672  *
9673  * Return:	1 on success, 0 otherwise
9674  */
9675 int smb3_check_sign_req(struct ksmbd_work *work)
9676 {
9677 	struct ksmbd_conn *conn = work->conn;
9678 	char *signing_key;
9679 	struct smb2_hdr *hdr;
9680 	struct channel *chann;
9681 	char signature_req[SMB2_SIGNATURE_SIZE];
9682 	char signature[SMB2_CMACAES_SIZE];
9683 	struct kvec iov[1];
9684 	size_t len;
9685 
9686 	hdr = smb_get_msg(work->request_buf);
9687 	if (work->next_smb2_rcv_hdr_off)
9688 		hdr = ksmbd_req_buf_next(work);
9689 
9690 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
9691 		len = get_rfc1002_len(work->request_buf);
9692 	else if (hdr->NextCommand)
9693 		len = le32_to_cpu(hdr->NextCommand);
9694 	else
9695 		len = get_rfc1002_len(work->request_buf) -
9696 			work->next_smb2_rcv_hdr_off;
9697 
9698 	if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
9699 		signing_key = work->sess->smb3signingkey;
9700 	} else {
9701 		chann = lookup_chann_list(work->sess, conn);
9702 		if (!chann) {
9703 			if (le16_to_cpu(hdr->Command) != SMB2_SESSION_SETUP_HE ||
9704 			    !(hdr->Flags & SMB2_FLAGS_SIGNED))
9705 				return 0;
9706 			signing_key = work->sess->smb3signingkey;
9707 		} else {
9708 			signing_key = chann->smb3signingkey;
9709 		}
9710 	}
9711 
9712 	if (!signing_key) {
9713 		pr_err("SMB3 signing key is not generated\n");
9714 		return 0;
9715 	}
9716 
9717 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
9718 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9719 	iov[0].iov_base = (char *)&hdr->ProtocolId;
9720 	iov[0].iov_len = len;
9721 
9722 	ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature);
9723 
9724 	if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
9725 		pr_err("bad smb2 signature\n");
9726 		return 0;
9727 	}
9728 
9729 	return 1;
9730 }
9731 
9732 /**
9733  * smb3_set_sign_rsp() - handler for rsp packet sign processing
9734  * @work:   smb work containing notify command buffer
9735  *
9736  */
9737 void smb3_set_sign_rsp(struct ksmbd_work *work)
9738 {
9739 	struct ksmbd_conn *conn = work->conn;
9740 	struct smb2_hdr *hdr;
9741 	struct channel *chann;
9742 	char signature[SMB2_CMACAES_SIZE];
9743 	struct kvec *iov;
9744 	u16 command = conn->ops->get_cmd_val(work);
9745 	int n_vec = 1;
9746 	char *signing_key;
9747 
9748 	hdr = ksmbd_resp_buf_curr(work);
9749 
9750 	if (command == SMB2_SESSION_SETUP_HE &&
9751 	    (!conn->binding || hdr->Status != STATUS_SUCCESS)) {
9752 		signing_key = work->sess->smb3signingkey;
9753 	} else {
9754 		chann = lookup_chann_list(work->sess, work->conn);
9755 		if (!chann) {
9756 			return;
9757 		}
9758 		signing_key = chann->smb3signingkey;
9759 	}
9760 
9761 	if (!signing_key)
9762 		return;
9763 
9764 	hdr->Flags |= SMB2_FLAGS_SIGNED;
9765 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9766 
9767 	if (hdr->Command == SMB2_READ) {
9768 		iov = &work->iov[work->iov_idx - 1];
9769 		n_vec++;
9770 	} else {
9771 		iov = &work->iov[work->iov_idx];
9772 	}
9773 
9774 	ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature);
9775 	memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
9776 }
9777 
9778 /**
9779  * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
9780  * @work:   smb work containing response buffer
9781  *
9782  */
9783 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
9784 {
9785 	struct ksmbd_conn *conn = work->conn;
9786 	struct ksmbd_session *sess = work->sess;
9787 	struct smb2_hdr *req, *rsp;
9788 
9789 	if (conn->dialect != SMB311_PROT_ID)
9790 		return;
9791 
9792 	WORK_BUFFERS(work, req, rsp);
9793 
9794 	if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE) {
9795 		ksmbd_conn_lock(conn);
9796 		if (conn->preauth_info)
9797 			ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9798 							 conn->preauth_info->Preauth_HashValue);
9799 		ksmbd_conn_unlock(conn);
9800 	}
9801 
9802 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
9803 		ksmbd_conn_lock(conn);
9804 
9805 		if (conn->binding) {
9806 			struct preauth_session *preauth_sess;
9807 
9808 			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
9809 			if (preauth_sess)
9810 				ksmbd_gen_preauth_integrity_hash(conn,
9811 					work->response_buf,
9812 					preauth_sess->Preauth_HashValue);
9813 		} else if (sess->Preauth_HashValue) {
9814 			ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9815 					 sess->Preauth_HashValue);
9816 		}
9817 		ksmbd_conn_unlock(conn);
9818 	}
9819 }
9820 
9821 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
9822 {
9823 	struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
9824 	struct smb2_hdr *hdr = smb_get_msg(old_buf);
9825 	unsigned int orig_len = get_rfc1002_len(old_buf);
9826 
9827 	/* tr_buf must be cleared by the caller */
9828 	tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
9829 	tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
9830 	tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
9831 	if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
9832 	    cipher_type == SMB2_ENCRYPTION_AES256_GCM)
9833 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
9834 	else
9835 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
9836 	memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
9837 	inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
9838 	inc_rfc1001_len(tr_buf, orig_len);
9839 }
9840 
9841 int smb3_encrypt_resp(struct ksmbd_work *work)
9842 {
9843 	struct kvec *iov = work->iov;
9844 	int rc = -ENOMEM;
9845 	void *tr_buf;
9846 
9847 	tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, KSMBD_DEFAULT_GFP);
9848 	if (!tr_buf)
9849 		return rc;
9850 
9851 	/* fill transform header */
9852 	fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
9853 
9854 	iov[0].iov_base = tr_buf;
9855 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9856 	work->tr_buf = tr_buf;
9857 
9858 	return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
9859 }
9860 
9861 bool smb3_is_transform_hdr(void *buf)
9862 {
9863 	struct smb2_transform_hdr *trhdr = smb_get_msg(buf);
9864 
9865 	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
9866 }
9867 
9868 int smb3_decrypt_req(struct ksmbd_work *work)
9869 {
9870 	struct ksmbd_session *sess;
9871 	char *buf = work->request_buf;
9872 	unsigned int pdu_length = get_rfc1002_len(buf);
9873 	struct kvec iov[2];
9874 	int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
9875 	struct smb2_transform_hdr *tr_hdr = smb_get_msg(buf);
9876 	int rc = 0;
9877 
9878 	if (pdu_length < sizeof(struct smb2_transform_hdr) ||
9879 	    buf_data_size < sizeof(struct smb2_hdr)) {
9880 		pr_err("Transform message is too small (%u)\n",
9881 		       pdu_length);
9882 		return -ECONNABORTED;
9883 	}
9884 
9885 	if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
9886 		pr_err("Transform message is broken\n");
9887 		return -ECONNABORTED;
9888 	}
9889 
9890 	sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
9891 	if (!sess) {
9892 		pr_err("invalid session id(%llx) in transform header\n",
9893 		       le64_to_cpu(tr_hdr->SessionId));
9894 		return -ECONNABORTED;
9895 	}
9896 	ksmbd_user_session_put(sess);
9897 
9898 	iov[0].iov_base = buf;
9899 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9900 	iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
9901 	iov[1].iov_len = buf_data_size;
9902 	rc = ksmbd_crypt_message(work, iov, 2, 0);
9903 	if (rc)
9904 		return rc;
9905 
9906 	memmove(buf + 4, iov[1].iov_base, buf_data_size);
9907 	*(__be32 *)buf = cpu_to_be32(buf_data_size);
9908 
9909 	return rc;
9910 }
9911 
9912 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
9913 {
9914 	struct ksmbd_conn *conn = work->conn;
9915 	struct ksmbd_session *sess = work->sess;
9916 	struct smb2_hdr *rsp = smb_get_msg(work->response_buf);
9917 
9918 	if (conn->dialect < SMB30_PROT_ID)
9919 		return false;
9920 
9921 	if (work->next_smb2_rcv_hdr_off)
9922 		rsp = ksmbd_resp_buf_next(work);
9923 
9924 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
9925 	    sess->user && !user_guest(sess->user) &&
9926 	    rsp->Status == STATUS_SUCCESS)
9927 		return true;
9928 	return false;
9929 }
9930