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