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