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