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