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