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