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