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