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