1 // SPDX-License-Identifier: LGPL-2.1
4 * Copyright (C) International Business Machines Corp., 2002,2011
5 * Author(s): Steve French (sfrench@us.ibm.com)
10 #include <linux/string.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/signal.h>
13 #include <linux/list.h>
14 #include <linux/wait.h>
15 #include <linux/slab.h>
16 #include <linux/pagemap.h>
17 #include <linux/ctype.h>
18 #include <linux/utsname.h>
19 #include <linux/mempool.h>
20 #include <linux/delay.h>
21 #include <linux/completion.h>
22 #include <linux/kthread.h>
23 #include <linux/pagevec.h>
24 #include <linux/freezer.h>
25 #include <linux/namei.h>
26 #include <linux/uuid.h>
27 #include <linux/uaccess.h>
28 #include <asm/processor.h>
29 #include <linux/inet.h>
30 #include <linux/module.h>
31 #include <keys/user-type.h>
33 #include <linux/parser.h>
34 #include <linux/bvec.h>
37 #include "cifsproto.h"
38 #include "cifs_unicode.h"
39 #include "cifs_debug.h"
40 #include "cifs_fs_sb.h"
43 #include "rfc1002pdu.h"
45 #include "smb2proto.h"
46 #include "smbdirect.h"
47 #include "dns_resolve.h"
48 #ifdef CONFIG_CIFS_DFS_UPCALL
49 #include "dfs_cache.h"
51 #include "fs_context.h"
54 extern mempool_t *cifs_req_poolp;
55 extern bool disable_legacy_dialects;
57 /* FIXME: should these be tunable? */
58 #define TLINK_ERROR_EXPIRE (1 * HZ)
59 #define TLINK_IDLE_EXPIRE (600 * HZ)
61 /* Drop the connection to not overload the server */
62 #define NUM_STATUS_IO_TIMEOUT 5
65 struct cifs_sb_info *cifs_sb;
66 struct smb3_fs_context *fs_ctx;
68 struct TCP_Server_Info *server;
70 struct cifs_tcon *tcon;
71 #ifdef CONFIG_CIFS_DFS_UPCALL
72 struct cifs_ses *root_ses;
74 char *origin_fullpath, *leaf_fullpath;
78 static int ip_connect(struct TCP_Server_Info *server);
79 static int generic_ip_connect(struct TCP_Server_Info *server);
80 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
81 static void cifs_prune_tlinks(struct work_struct *work);
84 * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
85 * get their ip addresses changed at some point.
87 * This should be called with server->srv_mutex held.
89 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
93 char *unc, *ipaddr = NULL;
95 unsigned long ttl = SMB_DNS_RESOLVE_INTERVAL_DEFAULT;
97 if (!server->hostname)
100 len = strlen(server->hostname) + 3;
102 unc = kmalloc(len, GFP_KERNEL);
104 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
107 scnprintf(unc, len, "\\\\%s", server->hostname);
109 rc = dns_resolve_server_name_to_ip(unc, &ipaddr, &expiry);
113 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
114 __func__, server->hostname, rc);
115 goto requeue_resolve;
118 spin_lock(&cifs_tcp_ses_lock);
119 rc = cifs_convert_address((struct sockaddr *)&server->dstaddr, ipaddr,
121 spin_unlock(&cifs_tcp_ses_lock);
124 /* rc == 1 means success here */
126 now = ktime_get_real_seconds();
127 if (expiry && expiry > now)
129 * To make sure we don't use the cached entry, retry 1s
132 ttl = max_t(unsigned long, expiry - now, SMB_DNS_RESOLVE_INTERVAL_MIN) + 1;
137 cifs_dbg(FYI, "%s: next dns resolution scheduled for %lu seconds in the future\n",
139 mod_delayed_work(cifsiod_wq, &server->resolve, (ttl * HZ));
145 static void cifs_resolve_server(struct work_struct *work)
148 struct TCP_Server_Info *server = container_of(work,
149 struct TCP_Server_Info, resolve.work);
151 mutex_lock(&server->srv_mutex);
154 * Resolve the hostname again to make sure that IP address is up-to-date.
156 rc = reconn_set_ipaddr_from_hostname(server);
158 cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
162 mutex_unlock(&server->srv_mutex);
166 * Mark all sessions and tcons for reconnect.
168 * @server needs to be previously set to CifsNeedReconnect.
170 static void cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server)
172 struct list_head *tmp, *tmp2;
173 struct cifs_ses *ses;
174 struct cifs_tcon *tcon;
175 struct mid_q_entry *mid_entry;
176 struct list_head retry_list;
179 server->max_read = 0;
181 cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
182 trace_smb3_reconnect(server->CurrentMid, server->conn_id, server->hostname);
184 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
185 * are not used until reconnected.
187 cifs_dbg(FYI, "%s: marking sessions and tcons for reconnect\n", __func__);
188 spin_lock(&cifs_tcp_ses_lock);
189 list_for_each(tmp, &server->smb_ses_list) {
190 ses = list_entry(tmp, struct cifs_ses, smb_ses_list);
191 ses->need_reconnect = true;
192 list_for_each(tmp2, &ses->tcon_list) {
193 tcon = list_entry(tmp2, struct cifs_tcon, tcon_list);
194 tcon->need_reconnect = true;
197 ses->tcon_ipc->need_reconnect = true;
199 spin_unlock(&cifs_tcp_ses_lock);
201 /* do not want to be sending data on a socket we are freeing */
202 cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
203 mutex_lock(&server->srv_mutex);
204 if (server->ssocket) {
205 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
206 server->ssocket->flags);
207 kernel_sock_shutdown(server->ssocket, SHUT_WR);
208 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
209 server->ssocket->flags);
210 sock_release(server->ssocket);
211 server->ssocket = NULL;
213 server->sequence_number = 0;
214 server->session_estab = false;
215 kfree(server->session_key.response);
216 server->session_key.response = NULL;
217 server->session_key.len = 0;
218 server->lstrp = jiffies;
220 /* mark submitted MIDs for retry and issue callback */
221 INIT_LIST_HEAD(&retry_list);
222 cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
223 spin_lock(&GlobalMid_Lock);
224 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
225 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
226 kref_get(&mid_entry->refcount);
227 if (mid_entry->mid_state == MID_REQUEST_SUBMITTED)
228 mid_entry->mid_state = MID_RETRY_NEEDED;
229 list_move(&mid_entry->qhead, &retry_list);
230 mid_entry->mid_flags |= MID_DELETED;
232 spin_unlock(&GlobalMid_Lock);
233 mutex_unlock(&server->srv_mutex);
235 cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
236 list_for_each_safe(tmp, tmp2, &retry_list) {
237 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
238 list_del_init(&mid_entry->qhead);
239 mid_entry->callback(mid_entry);
240 cifs_mid_q_entry_release(mid_entry);
243 if (cifs_rdma_enabled(server)) {
244 mutex_lock(&server->srv_mutex);
245 smbd_destroy(server);
246 mutex_unlock(&server->srv_mutex);
250 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
252 spin_lock(&GlobalMid_Lock);
253 server->nr_targets = num_targets;
254 if (server->tcpStatus == CifsExiting) {
255 /* the demux thread will exit normally next time through the loop */
256 spin_unlock(&GlobalMid_Lock);
257 wake_up(&server->response_q);
260 server->tcpStatus = CifsNeedReconnect;
261 spin_unlock(&GlobalMid_Lock);
266 * cifs tcp session reconnection
268 * mark tcp session as reconnecting so temporarily locked
269 * mark all smb sessions as reconnecting for tcp session
270 * reconnect tcp session
271 * wake up waiters on reconnection? - (not needed currently)
273 static int __cifs_reconnect(struct TCP_Server_Info *server)
277 if (!cifs_tcp_ses_needs_reconnect(server, 1))
280 cifs_mark_tcp_ses_conns_for_reconnect(server);
284 mutex_lock(&server->srv_mutex);
286 if (!cifs_swn_set_server_dstaddr(server)) {
287 /* resolve the hostname again to make sure that IP address is up-to-date */
288 rc = reconn_set_ipaddr_from_hostname(server);
289 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
292 if (cifs_rdma_enabled(server))
293 rc = smbd_reconnect(server);
295 rc = generic_ip_connect(server);
297 mutex_unlock(&server->srv_mutex);
298 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
301 atomic_inc(&tcpSesReconnectCount);
302 set_credits(server, 1);
303 spin_lock(&GlobalMid_Lock);
304 if (server->tcpStatus != CifsExiting)
305 server->tcpStatus = CifsNeedNegotiate;
306 spin_unlock(&GlobalMid_Lock);
307 cifs_swn_reset_server_dstaddr(server);
308 mutex_unlock(&server->srv_mutex);
310 } while (server->tcpStatus == CifsNeedReconnect);
312 if (server->tcpStatus == CifsNeedNegotiate)
313 mod_delayed_work(cifsiod_wq, &server->echo, 0);
315 wake_up(&server->response_q);
319 #ifdef CONFIG_CIFS_DFS_UPCALL
320 static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
325 if (!cifs_swn_set_server_dstaddr(server)) {
326 if (server->hostname != target) {
327 hostname = extract_hostname(target);
328 if (!IS_ERR(hostname)) {
329 kfree(server->hostname);
330 server->hostname = hostname;
332 cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
333 __func__, PTR_ERR(hostname));
334 cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
338 /* resolve the hostname again to make sure that IP address is up-to-date. */
339 rc = reconn_set_ipaddr_from_hostname(server);
340 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
342 /* Reconnect the socket */
343 if (cifs_rdma_enabled(server))
344 rc = smbd_reconnect(server);
346 rc = generic_ip_connect(server);
351 static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
352 struct dfs_cache_tgt_iterator **target_hint)
355 struct dfs_cache_tgt_iterator *tit;
359 /* If dfs target list is empty, then reconnect to last server */
360 tit = dfs_cache_get_tgt_iterator(tl);
362 return __reconnect_target_unlocked(server, server->hostname);
364 /* Otherwise, try every dfs target in @tl */
365 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
366 rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
375 static int reconnect_dfs_server(struct TCP_Server_Info *server)
378 const char *refpath = server->current_fullpath + 1;
379 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
380 struct dfs_cache_tgt_iterator *target_hint = NULL;
384 * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
386 * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
387 * targets (server->nr_targets). It's also possible that the cached referral was cleared
388 * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
389 * refreshing the referral, so, in this case, default it to 1.
391 if (!dfs_cache_noreq_find(refpath, NULL, &tl))
392 num_targets = dfs_cache_get_nr_tgts(&tl);
396 if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
399 cifs_mark_tcp_ses_conns_for_reconnect(server);
403 mutex_lock(&server->srv_mutex);
405 rc = reconnect_target_unlocked(server, &tl, &target_hint);
407 /* Failed to reconnect socket */
408 mutex_unlock(&server->srv_mutex);
409 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
414 * Socket was created. Update tcp session status to CifsNeedNegotiate so that a
415 * process waiting for reconnect will know it needs to re-establish session and tcon
416 * through the reconnected target server.
418 atomic_inc(&tcpSesReconnectCount);
419 set_credits(server, 1);
420 spin_lock(&GlobalMid_Lock);
421 if (server->tcpStatus != CifsExiting)
422 server->tcpStatus = CifsNeedNegotiate;
423 spin_unlock(&GlobalMid_Lock);
424 cifs_swn_reset_server_dstaddr(server);
425 mutex_unlock(&server->srv_mutex);
426 } while (server->tcpStatus == CifsNeedReconnect);
429 dfs_cache_noreq_update_tgthint(refpath, target_hint);
431 dfs_cache_free_tgts(&tl);
433 /* Need to set up echo worker again once connection has been established */
434 if (server->tcpStatus == CifsNeedNegotiate)
435 mod_delayed_work(cifsiod_wq, &server->echo, 0);
437 wake_up(&server->response_q);
441 int cifs_reconnect(struct TCP_Server_Info *server)
443 /* If tcp session is not an dfs connection, then reconnect to last target server */
444 spin_lock(&cifs_tcp_ses_lock);
445 if (!server->is_dfs_conn || !server->origin_fullpath || !server->leaf_fullpath) {
446 spin_unlock(&cifs_tcp_ses_lock);
447 return __cifs_reconnect(server);
449 spin_unlock(&cifs_tcp_ses_lock);
451 return reconnect_dfs_server(server);
454 int cifs_reconnect(struct TCP_Server_Info *server)
456 return __cifs_reconnect(server);
461 cifs_echo_request(struct work_struct *work)
464 struct TCP_Server_Info *server = container_of(work,
465 struct TCP_Server_Info, echo.work);
468 * We cannot send an echo if it is disabled.
469 * Also, no need to ping if we got a response recently.
472 if (server->tcpStatus == CifsNeedReconnect ||
473 server->tcpStatus == CifsExiting ||
474 server->tcpStatus == CifsNew ||
475 (server->ops->can_echo && !server->ops->can_echo(server)) ||
476 time_before(jiffies, server->lstrp + server->echo_interval - HZ))
479 rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
481 cifs_dbg(FYI, "Unable to send echo request to server: %s\n",
484 /* Check witness registrations */
488 queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
492 allocate_buffers(struct TCP_Server_Info *server)
494 if (!server->bigbuf) {
495 server->bigbuf = (char *)cifs_buf_get();
496 if (!server->bigbuf) {
497 cifs_server_dbg(VFS, "No memory for large SMB response\n");
499 /* retry will check if exiting */
502 } else if (server->large_buf) {
503 /* we are reusing a dirty large buf, clear its start */
504 memset(server->bigbuf, 0, HEADER_SIZE(server));
507 if (!server->smallbuf) {
508 server->smallbuf = (char *)cifs_small_buf_get();
509 if (!server->smallbuf) {
510 cifs_server_dbg(VFS, "No memory for SMB response\n");
512 /* retry will check if exiting */
515 /* beginning of smb buffer is cleared in our buf_get */
517 /* if existing small buf clear beginning */
518 memset(server->smallbuf, 0, HEADER_SIZE(server));
525 server_unresponsive(struct TCP_Server_Info *server)
528 * We need to wait 3 echo intervals to make sure we handle such
530 * 1s client sends a normal SMB request
531 * 2s client gets a response
532 * 30s echo workqueue job pops, and decides we got a response recently
533 * and don't need to send another
535 * 65s kernel_recvmsg times out, and we see that we haven't gotten
536 * a response in >60s.
538 if ((server->tcpStatus == CifsGood ||
539 server->tcpStatus == CifsNeedNegotiate) &&
540 (!server->ops->can_echo || server->ops->can_echo(server)) &&
541 time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
542 cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
543 (3 * server->echo_interval) / HZ);
544 cifs_reconnect(server);
552 zero_credits(struct TCP_Server_Info *server)
556 spin_lock(&server->req_lock);
557 val = server->credits + server->echo_credits + server->oplock_credits;
558 if (server->in_flight == 0 && val == 0) {
559 spin_unlock(&server->req_lock);
562 spin_unlock(&server->req_lock);
567 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
572 for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
575 /* reconnect if no credits and no requests in flight */
576 if (zero_credits(server)) {
577 cifs_reconnect(server);
578 return -ECONNABORTED;
581 if (server_unresponsive(server))
582 return -ECONNABORTED;
583 if (cifs_rdma_enabled(server) && server->smbd_conn)
584 length = smbd_recv(server->smbd_conn, smb_msg);
586 length = sock_recvmsg(server->ssocket, smb_msg, 0);
588 if (server->tcpStatus == CifsExiting)
591 if (server->tcpStatus == CifsNeedReconnect) {
592 cifs_reconnect(server);
593 return -ECONNABORTED;
596 if (length == -ERESTARTSYS ||
600 * Minimum sleep to prevent looping, allowing socket
601 * to clear and app threads to set tcpStatus
602 * CifsNeedReconnect if server hung.
604 usleep_range(1000, 2000);
610 cifs_dbg(FYI, "Received no data or error: %d\n", length);
611 cifs_reconnect(server);
612 return -ECONNABORTED;
619 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
620 unsigned int to_read)
622 struct msghdr smb_msg = {};
623 struct kvec iov = {.iov_base = buf, .iov_len = to_read};
624 iov_iter_kvec(&smb_msg.msg_iter, READ, &iov, 1, to_read);
626 return cifs_readv_from_socket(server, &smb_msg);
630 cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
632 struct msghdr smb_msg = {};
635 * iov_iter_discard already sets smb_msg.type and count and iov_offset
636 * and cifs_readv_from_socket sets msg_control and msg_controllen
637 * so little to initialize in struct msghdr
639 iov_iter_discard(&smb_msg.msg_iter, READ, to_read);
641 return cifs_readv_from_socket(server, &smb_msg);
645 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
646 unsigned int page_offset, unsigned int to_read)
648 struct msghdr smb_msg = {};
649 struct bio_vec bv = {
650 .bv_page = page, .bv_len = to_read, .bv_offset = page_offset};
651 iov_iter_bvec(&smb_msg.msg_iter, READ, &bv, 1, to_read);
652 return cifs_readv_from_socket(server, &smb_msg);
656 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
659 * The first byte big endian of the length field,
660 * is actually not part of the length but the type
661 * with the most common, zero, as regular data.
664 case RFC1002_SESSION_MESSAGE:
665 /* Regular SMB response */
667 case RFC1002_SESSION_KEEP_ALIVE:
668 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
670 case RFC1002_POSITIVE_SESSION_RESPONSE:
671 cifs_dbg(FYI, "RFC 1002 positive session response\n");
673 case RFC1002_NEGATIVE_SESSION_RESPONSE:
675 * We get this from Windows 98 instead of an error on
676 * SMB negprot response.
678 cifs_dbg(FYI, "RFC 1002 negative session response\n");
679 /* give server a second to clean up */
682 * Always try 445 first on reconnect since we get NACK
683 * on some if we ever connected to port 139 (the NACK
684 * is since we do not begin with RFC1001 session
687 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
688 cifs_reconnect(server);
691 cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
692 cifs_reconnect(server);
699 dequeue_mid(struct mid_q_entry *mid, bool malformed)
701 #ifdef CONFIG_CIFS_STATS2
702 mid->when_received = jiffies;
704 spin_lock(&GlobalMid_Lock);
706 mid->mid_state = MID_RESPONSE_RECEIVED;
708 mid->mid_state = MID_RESPONSE_MALFORMED;
710 * Trying to handle/dequeue a mid after the send_recv()
711 * function has finished processing it is a bug.
713 if (mid->mid_flags & MID_DELETED)
714 pr_warn_once("trying to dequeue a deleted mid\n");
716 list_del_init(&mid->qhead);
717 mid->mid_flags |= MID_DELETED;
719 spin_unlock(&GlobalMid_Lock);
723 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
725 struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buffer;
728 * SMB1 does not use credits.
730 if (server->vals->header_preamble_size)
733 return le16_to_cpu(shdr->CreditRequest);
737 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
738 char *buf, int malformed)
740 if (server->ops->check_trans2 &&
741 server->ops->check_trans2(mid, server, buf, malformed))
743 mid->credits_received = smb2_get_credits_from_hdr(buf, server);
745 mid->large_buf = server->large_buf;
746 /* Was previous buf put in mpx struct for multi-rsp? */
747 if (!mid->multiRsp) {
748 /* smb buffer will be freed by user thread */
749 if (server->large_buf)
750 server->bigbuf = NULL;
752 server->smallbuf = NULL;
754 dequeue_mid(mid, malformed);
757 static void clean_demultiplex_info(struct TCP_Server_Info *server)
761 /* take it off the list, if it's not already */
762 spin_lock(&cifs_tcp_ses_lock);
763 list_del_init(&server->tcp_ses_list);
764 spin_unlock(&cifs_tcp_ses_lock);
766 cancel_delayed_work_sync(&server->echo);
767 cancel_delayed_work_sync(&server->resolve);
769 spin_lock(&GlobalMid_Lock);
770 server->tcpStatus = CifsExiting;
771 spin_unlock(&GlobalMid_Lock);
772 wake_up_all(&server->response_q);
774 /* check if we have blocked requests that need to free */
775 spin_lock(&server->req_lock);
776 if (server->credits <= 0)
778 spin_unlock(&server->req_lock);
780 * Although there should not be any requests blocked on this queue it
781 * can not hurt to be paranoid and try to wake up requests that may
782 * haven been blocked when more than 50 at time were on the wire to the
783 * same server - they now will see the session is in exit state and get
784 * out of SendReceive.
786 wake_up_all(&server->request_q);
787 /* give those requests time to exit */
789 if (cifs_rdma_enabled(server))
790 smbd_destroy(server);
791 if (server->ssocket) {
792 sock_release(server->ssocket);
793 server->ssocket = NULL;
796 if (!list_empty(&server->pending_mid_q)) {
797 struct list_head dispose_list;
798 struct mid_q_entry *mid_entry;
799 struct list_head *tmp, *tmp2;
801 INIT_LIST_HEAD(&dispose_list);
802 spin_lock(&GlobalMid_Lock);
803 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
804 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
805 cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
806 kref_get(&mid_entry->refcount);
807 mid_entry->mid_state = MID_SHUTDOWN;
808 list_move(&mid_entry->qhead, &dispose_list);
809 mid_entry->mid_flags |= MID_DELETED;
811 spin_unlock(&GlobalMid_Lock);
813 /* now walk dispose list and issue callbacks */
814 list_for_each_safe(tmp, tmp2, &dispose_list) {
815 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
816 cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
817 list_del_init(&mid_entry->qhead);
818 mid_entry->callback(mid_entry);
819 cifs_mid_q_entry_release(mid_entry);
821 /* 1/8th of sec is more than enough time for them to exit */
825 if (!list_empty(&server->pending_mid_q)) {
827 * mpx threads have not exited yet give them at least the smb
828 * send timeout time for long ops.
830 * Due to delays on oplock break requests, we need to wait at
831 * least 45 seconds before giving up on a request getting a
832 * response and going ahead and killing cifsd.
834 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
837 * If threads still have not exited they are probably never
838 * coming home not much else we can do but free the memory.
842 #ifdef CONFIG_CIFS_DFS_UPCALL
843 kfree(server->origin_fullpath);
844 kfree(server->leaf_fullpath);
848 length = atomic_dec_return(&tcpSesAllocCount);
850 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
854 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
857 char *buf = server->smallbuf;
858 unsigned int pdu_length = server->pdu_size;
860 /* make sure this will fit in a large buffer */
861 if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
862 server->vals->header_preamble_size) {
863 cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
864 cifs_reconnect(server);
865 return -ECONNABORTED;
868 /* switch to large buffer if too big for a small one */
869 if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
870 server->large_buf = true;
871 memcpy(server->bigbuf, buf, server->total_read);
872 buf = server->bigbuf;
875 /* now read the rest */
876 length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
877 pdu_length - HEADER_SIZE(server) + 1
878 + server->vals->header_preamble_size);
882 server->total_read += length;
884 dump_smb(buf, server->total_read);
886 return cifs_handle_standard(server, mid);
890 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
892 char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
896 * We know that we received enough to get to the MID as we
897 * checked the pdu_length earlier. Now check to see
898 * if the rest of the header is OK. We borrow the length
899 * var for the rest of the loop to avoid a new stack var.
901 * 48 bytes is enough to display the header and a little bit
902 * into the payload for debugging purposes.
904 length = server->ops->check_message(buf, server->total_read, server);
906 cifs_dump_mem("Bad SMB: ", buf,
907 min_t(unsigned int, server->total_read, 48));
909 if (server->ops->is_session_expired &&
910 server->ops->is_session_expired(buf)) {
911 cifs_reconnect(server);
915 if (server->ops->is_status_pending &&
916 server->ops->is_status_pending(buf, server))
922 handle_mid(mid, server, buf, length);
927 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
929 struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buffer;
930 int scredits, in_flight;
933 * SMB1 does not use credits.
935 if (server->vals->header_preamble_size)
938 if (shdr->CreditRequest) {
939 spin_lock(&server->req_lock);
940 server->credits += le16_to_cpu(shdr->CreditRequest);
941 scredits = server->credits;
942 in_flight = server->in_flight;
943 spin_unlock(&server->req_lock);
944 wake_up(&server->request_q);
946 trace_smb3_add_credits(server->CurrentMid,
947 server->conn_id, server->hostname, scredits,
948 le16_to_cpu(shdr->CreditRequest), in_flight);
949 cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
950 __func__, le16_to_cpu(shdr->CreditRequest),
957 cifs_demultiplex_thread(void *p)
959 int i, num_mids, length;
960 struct TCP_Server_Info *server = p;
961 unsigned int pdu_length;
962 unsigned int next_offset;
964 struct task_struct *task_to_wake = NULL;
965 struct mid_q_entry *mids[MAX_COMPOUND];
966 char *bufs[MAX_COMPOUND];
967 unsigned int noreclaim_flag, num_io_timeout = 0;
969 noreclaim_flag = memalloc_noreclaim_save();
970 cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
972 length = atomic_inc_return(&tcpSesAllocCount);
974 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
977 allow_kernel_signal(SIGKILL);
978 while (server->tcpStatus != CifsExiting) {
982 if (!allocate_buffers(server))
985 server->large_buf = false;
986 buf = server->smallbuf;
987 pdu_length = 4; /* enough to get RFC1001 header */
989 length = cifs_read_from_socket(server, buf, pdu_length);
993 if (server->vals->header_preamble_size == 0)
994 server->total_read = 0;
996 server->total_read = length;
999 * The right amount was read from socket - 4 bytes,
1000 * so we can now interpret the length field.
1002 pdu_length = get_rfc1002_length(buf);
1004 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1005 if (!is_smb_response(server, buf[0]))
1008 server->pdu_size = pdu_length;
1010 /* make sure we have enough to get to the MID */
1011 if (server->pdu_size < HEADER_SIZE(server) - 1 -
1012 server->vals->header_preamble_size) {
1013 cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1015 cifs_reconnect(server);
1019 /* read down to the MID */
1020 length = cifs_read_from_socket(server,
1021 buf + server->vals->header_preamble_size,
1022 HEADER_SIZE(server) - 1
1023 - server->vals->header_preamble_size);
1026 server->total_read += length;
1028 if (server->ops->next_header) {
1029 next_offset = server->ops->next_header(buf);
1031 server->pdu_size = next_offset;
1034 memset(mids, 0, sizeof(mids));
1035 memset(bufs, 0, sizeof(bufs));
1038 if (server->ops->is_transform_hdr &&
1039 server->ops->receive_transform &&
1040 server->ops->is_transform_hdr(buf)) {
1041 length = server->ops->receive_transform(server,
1046 mids[0] = server->ops->find_mid(server, buf);
1050 if (!mids[0] || !mids[0]->receive)
1051 length = standard_receive3(server, mids[0]);
1053 length = mids[0]->receive(server, mids[0]);
1057 for (i = 0; i < num_mids; i++)
1059 cifs_mid_q_entry_release(mids[i]);
1063 if (server->ops->is_status_io_timeout &&
1064 server->ops->is_status_io_timeout(buf)) {
1066 if (num_io_timeout > NUM_STATUS_IO_TIMEOUT) {
1067 cifs_reconnect(server);
1073 server->lstrp = jiffies;
1075 for (i = 0; i < num_mids; i++) {
1076 if (mids[i] != NULL) {
1077 mids[i]->resp_buf_size = server->pdu_size;
1079 if (bufs[i] && server->ops->is_network_name_deleted)
1080 server->ops->is_network_name_deleted(bufs[i],
1083 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1084 mids[i]->callback(mids[i]);
1086 cifs_mid_q_entry_release(mids[i]);
1087 } else if (server->ops->is_oplock_break &&
1088 server->ops->is_oplock_break(bufs[i],
1090 smb2_add_credits_from_hdr(bufs[i], server);
1091 cifs_dbg(FYI, "Received oplock break\n");
1093 cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1094 atomic_read(&midCount));
1095 cifs_dump_mem("Received Data is: ", bufs[i],
1096 HEADER_SIZE(server));
1097 smb2_add_credits_from_hdr(bufs[i], server);
1098 #ifdef CONFIG_CIFS_DEBUG2
1099 if (server->ops->dump_detail)
1100 server->ops->dump_detail(bufs[i],
1102 cifs_dump_mids(server);
1103 #endif /* CIFS_DEBUG2 */
1107 if (pdu_length > server->pdu_size) {
1108 if (!allocate_buffers(server))
1110 pdu_length -= server->pdu_size;
1111 server->total_read = 0;
1112 server->large_buf = false;
1113 buf = server->smallbuf;
1116 } /* end while !EXITING */
1118 /* buffer usually freed in free_mid - need to free it here on exit */
1119 cifs_buf_release(server->bigbuf);
1120 if (server->smallbuf) /* no sense logging a debug message if NULL */
1121 cifs_small_buf_release(server->smallbuf);
1123 task_to_wake = xchg(&server->tsk, NULL);
1124 clean_demultiplex_info(server);
1126 /* if server->tsk was NULL then wait for a signal before exiting */
1127 if (!task_to_wake) {
1128 set_current_state(TASK_INTERRUPTIBLE);
1129 while (!signal_pending(current)) {
1131 set_current_state(TASK_INTERRUPTIBLE);
1133 set_current_state(TASK_RUNNING);
1136 memalloc_noreclaim_restore(noreclaim_flag);
1137 module_put_and_exit(0);
1141 * Returns true if srcaddr isn't specified and rhs isn't specified, or
1142 * if srcaddr is specified and matches the IP address of the rhs argument
1145 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1147 switch (srcaddr->sa_family) {
1149 return (rhs->sa_family == AF_UNSPEC);
1151 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1152 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1153 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1156 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1157 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1158 return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
1162 return false; /* don't expect to be here */
1167 * If no port is specified in addr structure, we try to match with 445 port
1168 * and if it fails - with 139 ports. It should be called only if address
1169 * families of server and addr are equal.
1172 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1174 __be16 port, *sport;
1176 /* SMBDirect manages its own ports, don't match it here */
1180 switch (addr->sa_family) {
1182 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1183 port = ((struct sockaddr_in *) addr)->sin_port;
1186 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1187 port = ((struct sockaddr_in6 *) addr)->sin6_port;
1195 port = htons(CIFS_PORT);
1199 port = htons(RFC1001_PORT);
1202 return port == *sport;
1206 match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
1207 struct sockaddr *srcaddr)
1209 switch (addr->sa_family) {
1211 struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
1212 struct sockaddr_in *srv_addr4 =
1213 (struct sockaddr_in *)&server->dstaddr;
1215 if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
1220 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
1221 struct sockaddr_in6 *srv_addr6 =
1222 (struct sockaddr_in6 *)&server->dstaddr;
1224 if (!ipv6_addr_equal(&addr6->sin6_addr,
1225 &srv_addr6->sin6_addr))
1227 if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
1233 return false; /* don't expect to be here */
1236 if (!cifs_match_ipaddr(srcaddr, (struct sockaddr *)&server->srcaddr))
1243 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1246 * The select_sectype function should either return the ctx->sectype
1247 * that was specified, or "Unspecified" if that sectype was not
1248 * compatible with the given NEGOTIATE request.
1250 if (server->ops->select_sectype(server, ctx->sectype)
1255 * Now check if signing mode is acceptable. No need to check
1256 * global_secflags at this point since if MUST_SIGN is set then
1257 * the server->sign had better be too.
1259 if (ctx->sign && !server->sign)
1265 static int match_server(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1267 struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1269 if (ctx->nosharesock)
1272 /* this server does not share socket */
1273 if (server->nosharesock)
1276 /* If multidialect negotiation see if existing sessions match one */
1277 if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1278 if (server->vals->protocol_id < SMB30_PROT_ID)
1280 } else if (strcmp(ctx->vals->version_string,
1281 SMBDEFAULT_VERSION_STRING) == 0) {
1282 if (server->vals->protocol_id < SMB21_PROT_ID)
1284 } else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1287 if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1290 if (strcasecmp(server->hostname, ctx->server_hostname))
1293 if (!match_address(server, addr,
1294 (struct sockaddr *)&ctx->srcaddr))
1297 if (!match_port(server, addr))
1300 if (!match_security(server, ctx))
1303 if (server->echo_interval != ctx->echo_interval * HZ)
1306 if (server->rdma != ctx->rdma)
1309 if (server->ignore_signature != ctx->ignore_signature)
1312 if (server->min_offload != ctx->min_offload)
1318 struct TCP_Server_Info *
1319 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1321 struct TCP_Server_Info *server;
1323 spin_lock(&cifs_tcp_ses_lock);
1324 list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1325 #ifdef CONFIG_CIFS_DFS_UPCALL
1327 * DFS failover implementation in cifs_reconnect() requires unique tcp sessions for
1328 * DFS connections to do failover properly, so avoid sharing them with regular
1329 * shares or even links that may connect to same server but having completely
1330 * different failover targets.
1332 if (server->is_dfs_conn)
1336 * Skip ses channels since they're only handled in lower layers
1337 * (e.g. cifs_send_recv).
1339 if (server->is_channel || !match_server(server, ctx))
1342 ++server->srv_count;
1343 spin_unlock(&cifs_tcp_ses_lock);
1344 cifs_dbg(FYI, "Existing tcp session with server found\n");
1347 spin_unlock(&cifs_tcp_ses_lock);
1352 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1354 struct task_struct *task;
1356 spin_lock(&cifs_tcp_ses_lock);
1357 if (--server->srv_count > 0) {
1358 spin_unlock(&cifs_tcp_ses_lock);
1362 /* srv_count can never go negative */
1363 WARN_ON(server->srv_count < 0);
1365 put_net(cifs_net_ns(server));
1367 list_del_init(&server->tcp_ses_list);
1368 spin_unlock(&cifs_tcp_ses_lock);
1370 cancel_delayed_work_sync(&server->echo);
1371 cancel_delayed_work_sync(&server->resolve);
1375 * Avoid deadlock here: reconnect work calls
1376 * cifs_put_tcp_session() at its end. Need to be sure
1377 * that reconnect work does nothing with server pointer after
1380 cancel_delayed_work(&server->reconnect);
1382 cancel_delayed_work_sync(&server->reconnect);
1384 spin_lock(&GlobalMid_Lock);
1385 server->tcpStatus = CifsExiting;
1386 spin_unlock(&GlobalMid_Lock);
1388 cifs_crypto_secmech_release(server);
1389 cifs_fscache_release_client_cookie(server);
1391 kfree(server->session_key.response);
1392 server->session_key.response = NULL;
1393 server->session_key.len = 0;
1394 kfree(server->hostname);
1395 server->hostname = NULL;
1397 task = xchg(&server->tsk, NULL);
1399 send_sig(SIGKILL, task, 1);
1402 struct TCP_Server_Info *
1403 cifs_get_tcp_session(struct smb3_fs_context *ctx)
1405 struct TCP_Server_Info *tcp_ses = NULL;
1408 cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1410 /* see if we already have a matching tcp_ses */
1411 tcp_ses = cifs_find_tcp_session(ctx);
1415 tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1421 tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1422 if (!tcp_ses->hostname) {
1427 if (ctx->nosharesock)
1428 tcp_ses->nosharesock = true;
1430 tcp_ses->ops = ctx->ops;
1431 tcp_ses->vals = ctx->vals;
1432 cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1434 tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1435 tcp_ses->noblockcnt = ctx->rootfs;
1436 tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1437 tcp_ses->noautotune = ctx->noautotune;
1438 tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1439 tcp_ses->rdma = ctx->rdma;
1440 tcp_ses->in_flight = 0;
1441 tcp_ses->max_in_flight = 0;
1442 tcp_ses->credits = 1;
1443 init_waitqueue_head(&tcp_ses->response_q);
1444 init_waitqueue_head(&tcp_ses->request_q);
1445 INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1446 mutex_init(&tcp_ses->srv_mutex);
1447 memcpy(tcp_ses->workstation_RFC1001_name,
1448 ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1449 memcpy(tcp_ses->server_RFC1001_name,
1450 ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1451 tcp_ses->session_estab = false;
1452 tcp_ses->sequence_number = 0;
1453 tcp_ses->reconnect_instance = 1;
1454 tcp_ses->lstrp = jiffies;
1455 tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1456 spin_lock_init(&tcp_ses->req_lock);
1457 INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1458 INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1459 INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1460 INIT_DELAYED_WORK(&tcp_ses->resolve, cifs_resolve_server);
1461 INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1462 mutex_init(&tcp_ses->reconnect_mutex);
1463 #ifdef CONFIG_CIFS_DFS_UPCALL
1464 mutex_init(&tcp_ses->refpath_lock);
1466 memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1467 sizeof(tcp_ses->srcaddr));
1468 memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1469 sizeof(tcp_ses->dstaddr));
1470 if (ctx->use_client_guid)
1471 memcpy(tcp_ses->client_guid, ctx->client_guid,
1472 SMB2_CLIENT_GUID_SIZE);
1474 generate_random_uuid(tcp_ses->client_guid);
1476 * at this point we are the only ones with the pointer
1477 * to the struct since the kernel thread not created yet
1478 * no need to spinlock this init of tcpStatus or srv_count
1480 tcp_ses->tcpStatus = CifsNew;
1481 ++tcp_ses->srv_count;
1483 if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1484 ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1485 tcp_ses->echo_interval = ctx->echo_interval * HZ;
1487 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1488 if (tcp_ses->rdma) {
1489 #ifndef CONFIG_CIFS_SMB_DIRECT
1490 cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1492 goto out_err_crypto_release;
1494 tcp_ses->smbd_conn = smbd_get_connection(
1495 tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1496 if (tcp_ses->smbd_conn) {
1497 cifs_dbg(VFS, "RDMA transport established\n");
1499 goto smbd_connected;
1502 goto out_err_crypto_release;
1505 rc = ip_connect(tcp_ses);
1507 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1508 goto out_err_crypto_release;
1512 * since we're in a cifs function already, we know that
1513 * this will succeed. No need for try_module_get().
1515 __module_get(THIS_MODULE);
1516 tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1518 if (IS_ERR(tcp_ses->tsk)) {
1519 rc = PTR_ERR(tcp_ses->tsk);
1520 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1521 module_put(THIS_MODULE);
1522 goto out_err_crypto_release;
1524 tcp_ses->min_offload = ctx->min_offload;
1526 * at this point we are the only ones with the pointer
1527 * to the struct since the kernel thread not created yet
1528 * no need to spinlock this update of tcpStatus
1530 tcp_ses->tcpStatus = CifsNeedNegotiate;
1532 if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1533 tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1535 tcp_ses->max_credits = ctx->max_credits;
1537 tcp_ses->nr_targets = 1;
1538 tcp_ses->ignore_signature = ctx->ignore_signature;
1539 /* thread spawned, put it on the list */
1540 spin_lock(&cifs_tcp_ses_lock);
1541 list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1542 spin_unlock(&cifs_tcp_ses_lock);
1544 cifs_fscache_get_client_cookie(tcp_ses);
1546 /* queue echo request delayed work */
1547 queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1549 /* queue dns resolution delayed work */
1550 cifs_dbg(FYI, "%s: next dns resolution scheduled for %d seconds in the future\n",
1551 __func__, SMB_DNS_RESOLVE_INTERVAL_DEFAULT);
1553 queue_delayed_work(cifsiod_wq, &tcp_ses->resolve, (SMB_DNS_RESOLVE_INTERVAL_DEFAULT * HZ));
1557 out_err_crypto_release:
1558 cifs_crypto_secmech_release(tcp_ses);
1560 put_net(cifs_net_ns(tcp_ses));
1564 kfree(tcp_ses->hostname);
1565 if (tcp_ses->ssocket)
1566 sock_release(tcp_ses->ssocket);
1572 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1574 if (ctx->sectype != Unspecified &&
1575 ctx->sectype != ses->sectype)
1579 * If an existing session is limited to less channels than
1580 * requested, it should not be reused
1582 spin_lock(&ses->chan_lock);
1583 if (ses->chan_max < ctx->max_channels) {
1584 spin_unlock(&ses->chan_lock);
1587 spin_unlock(&ses->chan_lock);
1589 switch (ses->sectype) {
1591 if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1595 /* NULL username means anonymous session */
1596 if (ses->user_name == NULL) {
1602 /* anything else takes username/password */
1603 if (strncmp(ses->user_name,
1604 ctx->username ? ctx->username : "",
1605 CIFS_MAX_USERNAME_LEN))
1607 if ((ctx->username && strlen(ctx->username) != 0) &&
1608 ses->password != NULL &&
1609 strncmp(ses->password,
1610 ctx->password ? ctx->password : "",
1611 CIFS_MAX_PASSWORD_LEN))
1618 * cifs_setup_ipc - helper to setup the IPC tcon for the session
1619 * @ses: smb session to issue the request on
1620 * @ctx: the superblock configuration context to use for building the
1621 * new tree connection for the IPC (interprocess communication RPC)
1623 * A new IPC connection is made and stored in the session
1624 * tcon_ipc. The IPC tcon has the same lifetime as the session.
1627 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1630 struct cifs_tcon *tcon;
1631 char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1633 struct TCP_Server_Info *server = ses->server;
1636 * If the mount request that resulted in the creation of the
1637 * session requires encryption, force IPC to be encrypted too.
1640 if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1643 cifs_server_dbg(VFS,
1644 "IPC: server doesn't support encryption\n");
1649 tcon = tconInfoAlloc();
1653 scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1659 rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1663 cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1668 cifs_dbg(FYI, "IPC tcon rc = %d ipc tid = %d\n", rc, tcon->tid);
1670 ses->tcon_ipc = tcon;
1676 * cifs_free_ipc - helper to release the session IPC tcon
1677 * @ses: smb session to unmount the IPC from
1679 * Needs to be called everytime a session is destroyed.
1681 * On session close, the IPC is closed and the server must release all tcons of the session.
1682 * No need to send a tree disconnect here.
1684 * Besides, it will make the server to not close durable and resilient files on session close, as
1685 * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1688 cifs_free_ipc(struct cifs_ses *ses)
1690 struct cifs_tcon *tcon = ses->tcon_ipc;
1696 ses->tcon_ipc = NULL;
1700 static struct cifs_ses *
1701 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1703 struct cifs_ses *ses;
1705 spin_lock(&cifs_tcp_ses_lock);
1706 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1707 if (ses->status == CifsExiting)
1709 if (!match_session(ses, ctx))
1712 spin_unlock(&cifs_tcp_ses_lock);
1715 spin_unlock(&cifs_tcp_ses_lock);
1719 void cifs_put_smb_ses(struct cifs_ses *ses)
1721 unsigned int rc, xid;
1722 unsigned int chan_count;
1723 struct TCP_Server_Info *server = ses->server;
1724 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1726 spin_lock(&cifs_tcp_ses_lock);
1727 if (ses->status == CifsExiting) {
1728 spin_unlock(&cifs_tcp_ses_lock);
1732 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1733 cifs_dbg(FYI, "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->treeName : "NONE");
1735 if (--ses->ses_count > 0) {
1736 spin_unlock(&cifs_tcp_ses_lock);
1739 spin_unlock(&cifs_tcp_ses_lock);
1741 /* ses_count can never go negative */
1742 WARN_ON(ses->ses_count < 0);
1744 spin_lock(&GlobalMid_Lock);
1745 if (ses->status == CifsGood)
1746 ses->status = CifsExiting;
1747 spin_unlock(&GlobalMid_Lock);
1751 if (ses->status == CifsExiting && server->ops->logoff) {
1753 rc = server->ops->logoff(xid, ses);
1755 cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
1760 spin_lock(&cifs_tcp_ses_lock);
1761 list_del_init(&ses->smb_ses_list);
1762 spin_unlock(&cifs_tcp_ses_lock);
1764 spin_lock(&ses->chan_lock);
1765 chan_count = ses->chan_count;
1766 spin_unlock(&ses->chan_lock);
1768 /* close any extra channels */
1769 if (chan_count > 1) {
1772 for (i = 1; i < chan_count; i++) {
1774 * note: for now, we're okay accessing ses->chans
1775 * without chan_lock. But when chans can go away, we'll
1776 * need to introduce ref counting to make sure that chan
1777 * is not freed from under us.
1779 cifs_put_tcp_session(ses->chans[i].server, 0);
1780 ses->chans[i].server = NULL;
1785 cifs_put_tcp_session(server, 0);
1790 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
1791 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
1793 /* Populate username and pw fields from keyring if possible */
1795 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
1799 const char *delim, *payload;
1803 struct TCP_Server_Info *server = ses->server;
1804 struct sockaddr_in *sa;
1805 struct sockaddr_in6 *sa6;
1806 const struct user_key_payload *upayload;
1808 desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
1812 /* try to find an address key first */
1813 switch (server->dstaddr.ss_family) {
1815 sa = (struct sockaddr_in *)&server->dstaddr;
1816 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
1819 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
1820 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
1823 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
1824 server->dstaddr.ss_family);
1829 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
1830 key = request_key(&key_type_logon, desc, "");
1832 if (!ses->domainName) {
1833 cifs_dbg(FYI, "domainName is NULL\n");
1838 /* didn't work, try to find a domain key */
1839 sprintf(desc, "cifs:d:%s", ses->domainName);
1840 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
1841 key = request_key(&key_type_logon, desc, "");
1849 down_read(&key->sem);
1850 upayload = user_key_payload_locked(key);
1851 if (IS_ERR_OR_NULL(upayload)) {
1852 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
1856 /* find first : in payload */
1857 payload = upayload->data;
1858 delim = strnchr(payload, upayload->datalen, ':');
1859 cifs_dbg(FYI, "payload=%s\n", payload);
1861 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
1867 len = delim - payload;
1868 if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
1869 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
1875 ctx->username = kstrndup(payload, len, GFP_KERNEL);
1876 if (!ctx->username) {
1877 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
1882 cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
1884 len = key->datalen - (len + 1);
1885 if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
1886 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
1888 kfree(ctx->username);
1889 ctx->username = NULL;
1894 ctx->password = kstrndup(delim, len, GFP_KERNEL);
1895 if (!ctx->password) {
1896 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
1899 kfree(ctx->username);
1900 ctx->username = NULL;
1905 * If we have a domain key then we must set the domainName in the
1908 if (is_domain && ses->domainName) {
1909 ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
1910 if (!ctx->domainname) {
1911 cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
1914 kfree(ctx->username);
1915 ctx->username = NULL;
1916 kfree_sensitive(ctx->password);
1917 ctx->password = NULL;
1927 cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
1930 #else /* ! CONFIG_KEYS */
1932 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
1933 struct cifs_ses *ses __attribute__((unused)))
1937 #endif /* CONFIG_KEYS */
1940 * cifs_get_smb_ses - get a session matching @ctx data from @server
1941 * @server: server to setup the session to
1942 * @ctx: superblock configuration context to use to setup the session
1944 * This function assumes it is being called from cifs_mount() where we
1945 * already got a server reference (server refcount +1). See
1946 * cifs_get_tcon() for refcount explanations.
1949 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1953 struct cifs_ses *ses;
1954 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
1955 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
1959 ses = cifs_find_smb_ses(server, ctx);
1961 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
1964 mutex_lock(&ses->session_mutex);
1965 rc = cifs_negotiate_protocol(xid, ses);
1967 mutex_unlock(&ses->session_mutex);
1968 /* problem -- put our ses reference */
1969 cifs_put_smb_ses(ses);
1973 if (ses->need_reconnect) {
1974 cifs_dbg(FYI, "Session needs reconnect\n");
1975 rc = cifs_setup_session(xid, ses,
1978 mutex_unlock(&ses->session_mutex);
1979 /* problem -- put our reference */
1980 cifs_put_smb_ses(ses);
1985 mutex_unlock(&ses->session_mutex);
1987 /* existing SMB ses has a server reference already */
1988 cifs_put_tcp_session(server, 0);
1995 cifs_dbg(FYI, "Existing smb sess not found\n");
1996 ses = sesInfoAlloc();
2000 /* new SMB session uses our server ref */
2001 ses->server = server;
2002 if (server->dstaddr.ss_family == AF_INET6)
2003 sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2005 sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2007 if (ctx->username) {
2008 ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2009 if (!ses->user_name)
2013 /* ctx->password freed at unmount */
2014 if (ctx->password) {
2015 ses->password = kstrdup(ctx->password, GFP_KERNEL);
2019 if (ctx->domainname) {
2020 ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2021 if (!ses->domainName)
2024 if (ctx->domainauto)
2025 ses->domainAuto = ctx->domainauto;
2026 ses->cred_uid = ctx->cred_uid;
2027 ses->linux_uid = ctx->linux_uid;
2029 ses->sectype = ctx->sectype;
2030 ses->sign = ctx->sign;
2031 mutex_lock(&ses->session_mutex);
2033 /* add server as first channel */
2034 spin_lock(&ses->chan_lock);
2035 ses->chans[0].server = server;
2036 ses->chan_count = 1;
2037 ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2038 spin_unlock(&ses->chan_lock);
2040 rc = cifs_negotiate_protocol(xid, ses);
2042 rc = cifs_setup_session(xid, ses, ctx->local_nls);
2044 /* each channel uses a different signing key */
2045 memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2046 sizeof(ses->smb3signingkey));
2048 mutex_unlock(&ses->session_mutex);
2052 /* success, put it on the list and add it as first channel */
2053 spin_lock(&cifs_tcp_ses_lock);
2054 list_add(&ses->smb_ses_list, &server->smb_ses_list);
2055 spin_unlock(&cifs_tcp_ses_lock);
2059 cifs_setup_ipc(ses, ctx);
2069 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2071 if (tcon->tidStatus == CifsExiting)
2073 if (strncmp(tcon->treeName, ctx->UNC, MAX_TREE_SIZE))
2075 if (tcon->seal != ctx->seal)
2077 if (tcon->snapshot_time != ctx->snapshot_time)
2079 if (tcon->handle_timeout != ctx->handle_timeout)
2081 if (tcon->no_lease != ctx->no_lease)
2083 if (tcon->nodelete != ctx->nodelete)
2088 static struct cifs_tcon *
2089 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2091 struct list_head *tmp;
2092 struct cifs_tcon *tcon;
2094 spin_lock(&cifs_tcp_ses_lock);
2095 list_for_each(tmp, &ses->tcon_list) {
2096 tcon = list_entry(tmp, struct cifs_tcon, tcon_list);
2098 if (!match_tcon(tcon, ctx))
2101 spin_unlock(&cifs_tcp_ses_lock);
2104 spin_unlock(&cifs_tcp_ses_lock);
2109 cifs_put_tcon(struct cifs_tcon *tcon)
2112 struct cifs_ses *ses;
2115 * IPC tcon share the lifetime of their session and are
2116 * destroyed in the session put function
2118 if (tcon == NULL || tcon->ipc)
2122 cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2123 spin_lock(&cifs_tcp_ses_lock);
2124 if (--tcon->tc_count > 0) {
2125 spin_unlock(&cifs_tcp_ses_lock);
2129 /* tc_count can never go negative */
2130 WARN_ON(tcon->tc_count < 0);
2132 if (tcon->use_witness) {
2135 rc = cifs_swn_unregister(tcon);
2137 cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2142 list_del_init(&tcon->tcon_list);
2143 spin_unlock(&cifs_tcp_ses_lock);
2146 if (ses->server->ops->tree_disconnect)
2147 ses->server->ops->tree_disconnect(xid, tcon);
2150 cifs_fscache_release_super_cookie(tcon);
2152 cifs_put_smb_ses(ses);
2156 * cifs_get_tcon - get a tcon matching @ctx data from @ses
2157 * @ses: smb session to issue the request on
2158 * @ctx: the superblock configuration context to use for building the
2160 * - tcon refcount is the number of mount points using the tcon.
2161 * - ses refcount is the number of tcon using the session.
2163 * 1. This function assumes it is being called from cifs_mount() where
2164 * we already got a session reference (ses refcount +1).
2166 * 2. Since we're in the context of adding a mount point, the end
2167 * result should be either:
2169 * a) a new tcon already allocated with refcount=1 (1 mount point) and
2170 * its session refcount incremented (1 new tcon). This +1 was
2171 * already done in (1).
2173 * b) an existing tcon with refcount+1 (add a mount point to it) and
2174 * identical ses refcount (no new tcon). Because of (1) we need to
2175 * decrement the ses refcount.
2177 static struct cifs_tcon *
2178 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2181 struct cifs_tcon *tcon;
2183 tcon = cifs_find_tcon(ses, ctx);
2186 * tcon has refcount already incremented but we need to
2187 * decrement extra ses reference gotten by caller (case b)
2189 cifs_dbg(FYI, "Found match on UNC path\n");
2190 cifs_put_smb_ses(ses);
2194 if (!ses->server->ops->tree_connect) {
2199 tcon = tconInfoAlloc();
2205 if (ctx->snapshot_time) {
2206 if (ses->server->vals->protocol_id == 0) {
2208 "Use SMB2 or later for snapshot mount option\n");
2212 tcon->snapshot_time = ctx->snapshot_time;
2215 if (ctx->handle_timeout) {
2216 if (ses->server->vals->protocol_id == 0) {
2218 "Use SMB2.1 or later for handle timeout option\n");
2222 tcon->handle_timeout = ctx->handle_timeout;
2226 if (ctx->password) {
2227 tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2228 if (!tcon->password) {
2235 if (ses->server->vals->protocol_id == 0) {
2237 "SMB3 or later required for encryption\n");
2240 } else if (tcon->ses->server->capabilities &
2241 SMB2_GLOBAL_CAP_ENCRYPTION)
2244 cifs_dbg(VFS, "Encryption is not supported on share\n");
2250 if (ctx->linux_ext) {
2251 if (ses->server->posix_ext_supported) {
2252 tcon->posix_extensions = true;
2253 pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2255 cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2262 * BB Do we need to wrap session_mutex around this TCon call and Unix
2263 * SetFS as we do on SessSetup and reconnect?
2266 rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2269 cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2273 tcon->use_persistent = false;
2274 /* check if SMB2 or later, CIFS does not support persistent handles */
2275 if (ctx->persistent) {
2276 if (ses->server->vals->protocol_id == 0) {
2278 "SMB3 or later required for persistent handles\n");
2281 } else if (ses->server->capabilities &
2282 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2283 tcon->use_persistent = true;
2284 else /* persistent handles requested but not supported */ {
2286 "Persistent handles not supported on share\n");
2290 } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2291 && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2292 && (ctx->nopersistent == false)) {
2293 cifs_dbg(FYI, "enabling persistent handles\n");
2294 tcon->use_persistent = true;
2295 } else if (ctx->resilient) {
2296 if (ses->server->vals->protocol_id == 0) {
2298 "SMB2.1 or later required for resilient handles\n");
2302 tcon->use_resilient = true;
2305 tcon->use_witness = false;
2306 if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2307 if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2308 if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2310 * Set witness in use flag in first place
2311 * to retry registration in the echo task
2313 tcon->use_witness = true;
2314 /* And try to register immediately */
2315 rc = cifs_swn_register(tcon);
2317 cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2321 /* TODO: try to extend for non-cluster uses (eg multichannel) */
2322 cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2327 cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2333 /* If the user really knows what they are doing they can override */
2334 if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2336 cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2337 else if (ctx->cache_rw)
2338 cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2341 if (ctx->no_lease) {
2342 if (ses->server->vals->protocol_id == 0) {
2344 "SMB2 or later required for nolease option\n");
2348 tcon->no_lease = ctx->no_lease;
2352 * We can have only one retry value for a connection to a share so for
2353 * resources mounted more than once to the same server share the last
2354 * value passed in for the retry flag is used.
2356 tcon->retry = ctx->retry;
2357 tcon->nocase = ctx->nocase;
2358 if (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING)
2359 tcon->nohandlecache = ctx->nohandlecache;
2361 tcon->nohandlecache = true;
2362 tcon->nodelete = ctx->nodelete;
2363 tcon->local_lease = ctx->local_lease;
2364 INIT_LIST_HEAD(&tcon->pending_opens);
2366 spin_lock(&cifs_tcp_ses_lock);
2367 list_add(&tcon->tcon_list, &ses->tcon_list);
2368 spin_unlock(&cifs_tcp_ses_lock);
2370 cifs_fscache_get_super_cookie(tcon);
2380 cifs_put_tlink(struct tcon_link *tlink)
2382 if (!tlink || IS_ERR(tlink))
2385 if (!atomic_dec_and_test(&tlink->tl_count) ||
2386 test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2387 tlink->tl_time = jiffies;
2391 if (!IS_ERR(tlink_tcon(tlink)))
2392 cifs_put_tcon(tlink_tcon(tlink));
2398 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2400 struct cifs_sb_info *old = CIFS_SB(sb);
2401 struct cifs_sb_info *new = mnt_data->cifs_sb;
2402 unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2403 unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2405 if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2408 if (old->mnt_cifs_serverino_autodisabled)
2409 newflags &= ~CIFS_MOUNT_SERVER_INUM;
2411 if (oldflags != newflags)
2415 * We want to share sb only if we don't specify an r/wsize or
2416 * specified r/wsize is greater than or equal to existing one.
2418 if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2421 if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2424 if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2425 !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2428 if (old->ctx->file_mode != new->ctx->file_mode ||
2429 old->ctx->dir_mode != new->ctx->dir_mode)
2432 if (strcmp(old->local_nls->charset, new->local_nls->charset))
2435 if (old->ctx->acregmax != new->ctx->acregmax)
2437 if (old->ctx->acdirmax != new->ctx->acdirmax)
2439 if (old->ctx->closetimeo != new->ctx->closetimeo)
2446 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2448 struct cifs_sb_info *old = CIFS_SB(sb);
2449 struct cifs_sb_info *new = mnt_data->cifs_sb;
2450 bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2452 bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2455 if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2457 else if (!old_set && !new_set)
2464 cifs_match_super(struct super_block *sb, void *data)
2466 struct cifs_mnt_data *mnt_data = (struct cifs_mnt_data *)data;
2467 struct smb3_fs_context *ctx;
2468 struct cifs_sb_info *cifs_sb;
2469 struct TCP_Server_Info *tcp_srv;
2470 struct cifs_ses *ses;
2471 struct cifs_tcon *tcon;
2472 struct tcon_link *tlink;
2475 spin_lock(&cifs_tcp_ses_lock);
2476 cifs_sb = CIFS_SB(sb);
2478 /* We do not want to use a superblock that has been shutdown */
2479 if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
2480 spin_unlock(&cifs_tcp_ses_lock);
2484 tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2485 if (tlink == NULL) {
2486 /* can not match superblock if tlink were ever null */
2487 spin_unlock(&cifs_tcp_ses_lock);
2490 tcon = tlink_tcon(tlink);
2492 tcp_srv = ses->server;
2494 ctx = mnt_data->ctx;
2496 if (!match_server(tcp_srv, ctx) ||
2497 !match_session(ses, ctx) ||
2498 !match_tcon(tcon, ctx) ||
2499 !match_prepath(sb, mnt_data)) {
2504 rc = compare_mount_options(sb, mnt_data);
2506 spin_unlock(&cifs_tcp_ses_lock);
2507 cifs_put_tlink(tlink);
2511 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2512 static struct lock_class_key cifs_key[2];
2513 static struct lock_class_key cifs_slock_key[2];
2516 cifs_reclassify_socket4(struct socket *sock)
2518 struct sock *sk = sock->sk;
2519 BUG_ON(!sock_allow_reclassification(sk));
2520 sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2521 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2525 cifs_reclassify_socket6(struct socket *sock)
2527 struct sock *sk = sock->sk;
2528 BUG_ON(!sock_allow_reclassification(sk));
2529 sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2530 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2534 cifs_reclassify_socket4(struct socket *sock)
2539 cifs_reclassify_socket6(struct socket *sock)
2544 /* See RFC1001 section 14 on representation of Netbios names */
2545 static void rfc1002mangle(char *target, char *source, unsigned int length)
2549 for (i = 0, j = 0; i < (length); i++) {
2550 /* mask a nibble at a time and encode */
2551 target[j] = 'A' + (0x0F & (source[i] >> 4));
2552 target[j+1] = 'A' + (0x0F & source[i]);
2559 bind_socket(struct TCP_Server_Info *server)
2562 if (server->srcaddr.ss_family != AF_UNSPEC) {
2563 /* Bind to the specified local IP address */
2564 struct socket *socket = server->ssocket;
2565 rc = socket->ops->bind(socket,
2566 (struct sockaddr *) &server->srcaddr,
2567 sizeof(server->srcaddr));
2569 struct sockaddr_in *saddr4;
2570 struct sockaddr_in6 *saddr6;
2571 saddr4 = (struct sockaddr_in *)&server->srcaddr;
2572 saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2573 if (saddr6->sin6_family == AF_INET6)
2574 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2575 &saddr6->sin6_addr, rc);
2577 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2578 &saddr4->sin_addr.s_addr, rc);
2585 ip_rfc1001_connect(struct TCP_Server_Info *server)
2589 * some servers require RFC1001 sessinit before sending
2590 * negprot - BB check reconnection in case where second
2591 * sessinit is sent but no second negprot
2593 struct rfc1002_session_packet *ses_init_buf;
2594 struct smb_hdr *smb_buf;
2595 ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
2598 ses_init_buf->trailer.session_req.called_len = 32;
2600 if (server->server_RFC1001_name[0] != 0)
2601 rfc1002mangle(ses_init_buf->trailer.
2602 session_req.called_name,
2603 server->server_RFC1001_name,
2604 RFC1001_NAME_LEN_WITH_NULL);
2606 rfc1002mangle(ses_init_buf->trailer.
2607 session_req.called_name,
2608 DEFAULT_CIFS_CALLED_NAME,
2609 RFC1001_NAME_LEN_WITH_NULL);
2611 ses_init_buf->trailer.session_req.calling_len = 32;
2614 * calling name ends in null (byte 16) from old smb
2617 if (server->workstation_RFC1001_name[0] != 0)
2618 rfc1002mangle(ses_init_buf->trailer.
2619 session_req.calling_name,
2620 server->workstation_RFC1001_name,
2621 RFC1001_NAME_LEN_WITH_NULL);
2623 rfc1002mangle(ses_init_buf->trailer.
2624 session_req.calling_name,
2626 RFC1001_NAME_LEN_WITH_NULL);
2628 ses_init_buf->trailer.session_req.scope1 = 0;
2629 ses_init_buf->trailer.session_req.scope2 = 0;
2630 smb_buf = (struct smb_hdr *)ses_init_buf;
2632 /* sizeof RFC1002_SESSION_REQUEST with no scope */
2633 smb_buf->smb_buf_length = cpu_to_be32(0x81000044);
2634 rc = smb_send(server, smb_buf, 0x44);
2635 kfree(ses_init_buf);
2637 * RFC1001 layer in at least one server
2638 * requires very short break before negprot
2639 * presumably because not expecting negprot
2640 * to follow so fast. This is a simple
2641 * solution that works without
2642 * complicating the code and causes no
2643 * significant slowing down on mount
2646 usleep_range(1000, 2000);
2649 * else the negprot may still work without this
2650 * even though malloc failed
2657 generic_ip_connect(struct TCP_Server_Info *server)
2662 struct socket *socket = server->ssocket;
2663 struct sockaddr *saddr;
2665 saddr = (struct sockaddr *) &server->dstaddr;
2667 if (server->dstaddr.ss_family == AF_INET6) {
2668 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
2670 sport = ipv6->sin6_port;
2671 slen = sizeof(struct sockaddr_in6);
2673 cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
2676 struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
2678 sport = ipv4->sin_port;
2679 slen = sizeof(struct sockaddr_in);
2681 cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
2685 if (socket == NULL) {
2686 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
2687 IPPROTO_TCP, &socket, 1);
2689 cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
2690 server->ssocket = NULL;
2694 /* BB other socket options to set KEEPALIVE, NODELAY? */
2695 cifs_dbg(FYI, "Socket created\n");
2696 server->ssocket = socket;
2697 socket->sk->sk_allocation = GFP_NOFS;
2698 if (sfamily == AF_INET6)
2699 cifs_reclassify_socket6(socket);
2701 cifs_reclassify_socket4(socket);
2704 rc = bind_socket(server);
2709 * Eventually check for other socket options to change from
2710 * the default. sock_setsockopt not used because it expects
2713 socket->sk->sk_rcvtimeo = 7 * HZ;
2714 socket->sk->sk_sndtimeo = 5 * HZ;
2716 /* make the bufsizes depend on wsize/rsize and max requests */
2717 if (server->noautotune) {
2718 if (socket->sk->sk_sndbuf < (200 * 1024))
2719 socket->sk->sk_sndbuf = 200 * 1024;
2720 if (socket->sk->sk_rcvbuf < (140 * 1024))
2721 socket->sk->sk_rcvbuf = 140 * 1024;
2724 if (server->tcp_nodelay)
2725 tcp_sock_set_nodelay(socket->sk);
2727 cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
2728 socket->sk->sk_sndbuf,
2729 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
2731 rc = socket->ops->connect(socket, saddr, slen,
2732 server->noblockcnt ? O_NONBLOCK : 0);
2734 * When mounting SMB root file systems, we do not want to block in
2735 * connect. Otherwise bail out and then let cifs_reconnect() perform
2736 * reconnect failover - if possible.
2738 if (server->noblockcnt && rc == -EINPROGRESS)
2741 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
2742 sock_release(socket);
2743 server->ssocket = NULL;
2747 if (sport == htons(RFC1001_PORT))
2748 rc = ip_rfc1001_connect(server);
2754 ip_connect(struct TCP_Server_Info *server)
2757 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2758 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2760 if (server->dstaddr.ss_family == AF_INET6)
2761 sport = &addr6->sin6_port;
2763 sport = &addr->sin_port;
2768 /* try with 445 port at first */
2769 *sport = htons(CIFS_PORT);
2771 rc = generic_ip_connect(server);
2775 /* if it failed, try with 139 port */
2776 *sport = htons(RFC1001_PORT);
2779 return generic_ip_connect(server);
2782 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
2783 struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
2786 * If we are reconnecting then should we check to see if
2787 * any requested capabilities changed locally e.g. via
2788 * remount but we can not do much about it here
2789 * if they have (even if we could detect it by the following)
2790 * Perhaps we could add a backpointer to array of sb from tcon
2791 * or if we change to make all sb to same share the same
2792 * sb as NFS - then we only have one backpointer to sb.
2793 * What if we wanted to mount the server share twice once with
2794 * and once without posixacls or posix paths?
2796 __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
2798 if (ctx && ctx->no_linux_ext) {
2799 tcon->fsUnixInfo.Capability = 0;
2800 tcon->unix_ext = 0; /* Unix Extensions disabled */
2801 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
2804 tcon->unix_ext = 1; /* Unix Extensions supported */
2806 if (!tcon->unix_ext) {
2807 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
2811 if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
2812 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
2813 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
2815 * check for reconnect case in which we do not
2816 * want to change the mount behavior if we can avoid it
2820 * turn off POSIX ACL and PATHNAMES if not set
2821 * originally at mount time
2823 if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
2824 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
2825 if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
2826 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
2827 cifs_dbg(VFS, "POSIXPATH support change\n");
2828 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
2829 } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
2830 cifs_dbg(VFS, "possible reconnect error\n");
2831 cifs_dbg(VFS, "server disabled POSIX path support\n");
2835 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
2836 cifs_dbg(VFS, "per-share encryption not supported yet\n");
2838 cap &= CIFS_UNIX_CAP_MASK;
2839 if (ctx && ctx->no_psx_acl)
2840 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
2841 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
2842 cifs_dbg(FYI, "negotiated posix acl support\n");
2844 cifs_sb->mnt_cifs_flags |=
2845 CIFS_MOUNT_POSIXACL;
2848 if (ctx && ctx->posix_paths == 0)
2849 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
2850 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
2851 cifs_dbg(FYI, "negotiate posix pathnames\n");
2853 cifs_sb->mnt_cifs_flags |=
2854 CIFS_MOUNT_POSIX_PATHS;
2857 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
2858 #ifdef CONFIG_CIFS_DEBUG2
2859 if (cap & CIFS_UNIX_FCNTL_CAP)
2860 cifs_dbg(FYI, "FCNTL cap\n");
2861 if (cap & CIFS_UNIX_EXTATTR_CAP)
2862 cifs_dbg(FYI, "EXTATTR cap\n");
2863 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
2864 cifs_dbg(FYI, "POSIX path cap\n");
2865 if (cap & CIFS_UNIX_XATTR_CAP)
2866 cifs_dbg(FYI, "XATTR cap\n");
2867 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
2868 cifs_dbg(FYI, "POSIX ACL cap\n");
2869 if (cap & CIFS_UNIX_LARGE_READ_CAP)
2870 cifs_dbg(FYI, "very large read cap\n");
2871 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
2872 cifs_dbg(FYI, "very large write cap\n");
2873 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
2874 cifs_dbg(FYI, "transport encryption cap\n");
2875 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
2876 cifs_dbg(FYI, "mandatory transport encryption cap\n");
2877 #endif /* CIFS_DEBUG2 */
2878 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
2880 cifs_dbg(FYI, "resetting capabilities failed\n");
2882 cifs_dbg(VFS, "Negotiating Unix capabilities with the server failed. Consider mounting with the Unix Extensions disabled if problems are found by specifying the nounix mount option.\n");
2888 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
2890 struct smb3_fs_context *ctx = cifs_sb->ctx;
2892 INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
2894 spin_lock_init(&cifs_sb->tlink_tree_lock);
2895 cifs_sb->tlink_tree = RB_ROOT;
2897 cifs_dbg(FYI, "file mode: %04ho dir mode: %04ho\n",
2898 ctx->file_mode, ctx->dir_mode);
2900 /* this is needed for ASCII cp to Unicode converts */
2901 if (ctx->iocharset == NULL) {
2902 /* load_nls_default cannot return null */
2903 cifs_sb->local_nls = load_nls_default();
2905 cifs_sb->local_nls = load_nls(ctx->iocharset);
2906 if (cifs_sb->local_nls == NULL) {
2907 cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
2912 ctx->local_nls = cifs_sb->local_nls;
2914 smb3_update_mnt_flags(cifs_sb);
2917 cifs_dbg(FYI, "mounting share using direct i/o\n");
2918 if (ctx->cache_ro) {
2919 cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
2920 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
2921 } else if (ctx->cache_rw) {
2922 cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
2923 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
2924 CIFS_MOUNT_RW_CACHE);
2927 if ((ctx->cifs_acl) && (ctx->dynperm))
2928 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
2931 cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
2932 if (cifs_sb->prepath == NULL)
2934 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
2940 /* Release all succeed connections */
2941 static inline void mount_put_conns(struct mount_ctx *mnt_ctx)
2946 cifs_put_tcon(mnt_ctx->tcon);
2947 else if (mnt_ctx->ses)
2948 cifs_put_smb_ses(mnt_ctx->ses);
2949 else if (mnt_ctx->server)
2950 cifs_put_tcp_session(mnt_ctx->server, 0);
2951 mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
2952 free_xid(mnt_ctx->xid);
2955 /* Get connections for tcp, ses and tcon */
2956 static int mount_get_conns(struct mount_ctx *mnt_ctx)
2959 struct TCP_Server_Info *server = NULL;
2960 struct cifs_ses *ses = NULL;
2961 struct cifs_tcon *tcon = NULL;
2962 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
2963 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
2968 /* get a reference to a tcp session */
2969 server = cifs_get_tcp_session(ctx);
2970 if (IS_ERR(server)) {
2971 rc = PTR_ERR(server);
2976 /* get a reference to a SMB session */
2977 ses = cifs_get_smb_ses(server, ctx);
2984 if ((ctx->persistent == true) && (!(ses->server->capabilities &
2985 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
2986 cifs_server_dbg(VFS, "persistent handles not supported by server\n");
2991 /* search for existing tcon to this server share */
2992 tcon = cifs_get_tcon(ses, ctx);
2999 /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3000 if (tcon->posix_extensions)
3001 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3003 /* tell server which Unix caps we support */
3004 if (cap_unix(tcon->ses)) {
3006 * reset of caps checks mount to see if unix extensions disabled
3007 * for just this mount.
3009 reset_cifs_unix_caps(xid, tcon, cifs_sb, ctx);
3010 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3011 (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3012 CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3017 tcon->unix_ext = 0; /* server does not support them */
3019 /* do not care if a following call succeed - informational */
3020 if (!tcon->pipe && server->ops->qfs_tcon) {
3021 server->ops->qfs_tcon(xid, tcon, cifs_sb);
3022 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3023 if (tcon->fsDevInfo.DeviceCharacteristics &
3024 cpu_to_le32(FILE_READ_ONLY_DEVICE))
3025 cifs_dbg(VFS, "mounted to read only share\n");
3026 else if ((cifs_sb->mnt_cifs_flags &
3027 CIFS_MOUNT_RW_CACHE) == 0)
3028 cifs_dbg(VFS, "read only mount of RW share\n");
3029 /* no need to log a RW mount of a typical RW share */
3034 * Clamp the rsize/wsize mount arguments if they are too big for the server
3035 * and set the rsize/wsize to the negotiated values if not passed in by
3038 if ((cifs_sb->ctx->wsize == 0) ||
3039 (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
3040 cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
3041 if ((cifs_sb->ctx->rsize == 0) ||
3042 (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3043 cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3046 mnt_ctx->server = server;
3048 mnt_ctx->tcon = tcon;
3054 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3055 struct cifs_tcon *tcon)
3057 struct tcon_link *tlink;
3059 /* hang the tcon off of the superblock */
3060 tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3064 tlink->tl_uid = ses->linux_uid;
3065 tlink->tl_tcon = tcon;
3066 tlink->tl_time = jiffies;
3067 set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3068 set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3070 cifs_sb->master_tlink = tlink;
3071 spin_lock(&cifs_sb->tlink_tree_lock);
3072 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3073 spin_unlock(&cifs_sb->tlink_tree_lock);
3075 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3080 #ifdef CONFIG_CIFS_DFS_UPCALL
3081 /* Get unique dfs connections */
3082 static int mount_get_dfs_conns(struct mount_ctx *mnt_ctx)
3086 mnt_ctx->fs_ctx->nosharesock = true;
3087 rc = mount_get_conns(mnt_ctx);
3088 if (mnt_ctx->server) {
3089 cifs_dbg(FYI, "%s: marking tcp session as a dfs connection\n", __func__);
3090 spin_lock(&cifs_tcp_ses_lock);
3091 mnt_ctx->server->is_dfs_conn = true;
3092 spin_unlock(&cifs_tcp_ses_lock);
3098 * cifs_build_path_to_root returns full path to root when we do not have an
3099 * existing connection (tcon)
3102 build_unc_path_to_root(const struct smb3_fs_context *ctx,
3103 const struct cifs_sb_info *cifs_sb, bool useppath)
3105 char *full_path, *pos;
3106 unsigned int pplen = useppath && ctx->prepath ?
3107 strlen(ctx->prepath) + 1 : 0;
3108 unsigned int unc_len = strnlen(ctx->UNC, MAX_TREE_SIZE + 1);
3110 if (unc_len > MAX_TREE_SIZE)
3111 return ERR_PTR(-EINVAL);
3113 full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
3114 if (full_path == NULL)
3115 return ERR_PTR(-ENOMEM);
3117 memcpy(full_path, ctx->UNC, unc_len);
3118 pos = full_path + unc_len;
3121 *pos = CIFS_DIR_SEP(cifs_sb);
3122 memcpy(pos + 1, ctx->prepath, pplen);
3126 *pos = '\0'; /* add trailing null */
3127 convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
3128 cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
3133 * expand_dfs_referral - Update cifs_sb from dfs referral path
3135 * cifs_sb->ctx->mount_options will be (re-)allocated to a string containing updated options for the
3136 * submount. Otherwise it will be left untouched.
3138 static int expand_dfs_referral(struct mount_ctx *mnt_ctx, const char *full_path,
3139 struct dfs_info3_param *referral)
3142 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3143 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3144 char *fake_devname = NULL, *mdata = NULL;
3146 mdata = cifs_compose_mount_options(cifs_sb->ctx->mount_options, full_path + 1, referral,
3148 if (IS_ERR(mdata)) {
3149 rc = PTR_ERR(mdata);
3153 * We can not clear out the whole structure since we no longer have an explicit
3154 * function to parse a mount-string. Instead we need to clear out the individual
3155 * fields that are no longer valid.
3157 kfree(ctx->prepath);
3158 ctx->prepath = NULL;
3159 rc = cifs_setup_volume_info(ctx, mdata, fake_devname);
3161 kfree(fake_devname);
3162 kfree(cifs_sb->ctx->mount_options);
3163 cifs_sb->ctx->mount_options = mdata;
3169 /* TODO: all callers to this are broken. We are not parsing mount_options here
3170 * we should pass a clone of the original context?
3173 cifs_setup_volume_info(struct smb3_fs_context *ctx, const char *mntopts, const char *devname)
3178 cifs_dbg(FYI, "%s: devname=%s\n", __func__, devname);
3179 rc = smb3_parse_devname(devname, ctx);
3181 cifs_dbg(VFS, "%s: failed to parse %s: %d\n", __func__, devname, rc);
3189 rc = smb3_parse_opt(mntopts, "ip", &ip);
3191 cifs_dbg(VFS, "%s: failed to parse ip options: %d\n", __func__, rc);
3195 rc = cifs_convert_address((struct sockaddr *)&ctx->dstaddr, ip, strlen(ip));
3198 cifs_dbg(VFS, "%s: failed to convert ip address\n", __func__);
3203 if (ctx->nullauth) {
3204 cifs_dbg(FYI, "Anonymous login\n");
3205 kfree(ctx->username);
3206 ctx->username = NULL;
3207 } else if (ctx->username) {
3208 /* BB fixme parse for domain name here */
3209 cifs_dbg(FYI, "Username: %s\n", ctx->username);
3211 cifs_dbg(VFS, "No username specified\n");
3212 /* In userspace mount helper we can get user name from alternate
3213 locations such as env variables and files on disk */
3221 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3223 struct cifs_tcon *tcon,
3224 struct cifs_sb_info *cifs_sb,
3231 int skip = added_treename ? 1 : 0;
3233 sep = CIFS_DIR_SEP(cifs_sb);
3236 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3238 /* skip separators */
3243 /* next separator */
3244 while (*s && *s != sep)
3247 * if the treename is added, we then have to skip the first
3248 * part within the separators
3255 * temporarily null-terminate the path at the end of
3256 * the current component
3260 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3268 * Check if path is remote (e.g. a DFS share). Return -EREMOTE if it is,
3271 static int is_path_remote(struct mount_ctx *mnt_ctx)
3274 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3275 struct TCP_Server_Info *server = mnt_ctx->server;
3276 unsigned int xid = mnt_ctx->xid;
3277 struct cifs_tcon *tcon = mnt_ctx->tcon;
3278 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3281 if (!server->ops->is_path_accessible)
3285 * cifs_build_path_to_root works only when we have a valid tcon
3287 full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3288 tcon->Flags & SMB_SHARE_IS_IN_DFS);
3289 if (full_path == NULL)
3292 cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3294 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3296 if (rc != 0 && rc != -EREMOTE) {
3301 if (rc != -EREMOTE) {
3302 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3303 cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3305 cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3306 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3315 #ifdef CONFIG_CIFS_DFS_UPCALL
3316 static void set_root_ses(struct mount_ctx *mnt_ctx)
3319 spin_lock(&cifs_tcp_ses_lock);
3320 mnt_ctx->ses->ses_count++;
3321 spin_unlock(&cifs_tcp_ses_lock);
3322 dfs_cache_add_refsrv_session(&mnt_ctx->mount_id, mnt_ctx->ses);
3324 mnt_ctx->root_ses = mnt_ctx->ses;
3327 static int is_dfs_mount(struct mount_ctx *mnt_ctx, bool *isdfs, struct dfs_cache_tgt_list *root_tl)
3330 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3331 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3335 rc = mount_get_conns(mnt_ctx);
3337 * If called with 'nodfs' mount option, then skip DFS resolving. Otherwise unconditionally
3338 * try to get an DFS referral (even cached) to determine whether it is an DFS mount.
3340 * Skip prefix path to provide support for DFS referrals from w2k8 servers which don't seem
3341 * to respond with PATH_NOT_COVERED to requests that include the prefix.
3343 if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
3344 dfs_cache_find(mnt_ctx->xid, mnt_ctx->ses, cifs_sb->local_nls, cifs_remap(cifs_sb),
3345 ctx->UNC + 1, NULL, root_tl)) {
3348 /* Check if it is fully accessible and then mount it */
3349 rc = is_path_remote(mnt_ctx);
3352 else if (rc != -EREMOTE)
3358 static int connect_dfs_target(struct mount_ctx *mnt_ctx, const char *full_path,
3359 const char *ref_path, struct dfs_cache_tgt_iterator *tit)
3362 struct dfs_info3_param ref = {};
3363 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3364 char *oldmnt = cifs_sb->ctx->mount_options;
3366 rc = dfs_cache_get_tgt_referral(ref_path, tit, &ref);
3370 rc = expand_dfs_referral(mnt_ctx, full_path, &ref);
3374 /* Connect to new target only if we were redirected (e.g. mount options changed) */
3375 if (oldmnt != cifs_sb->ctx->mount_options) {
3376 mount_put_conns(mnt_ctx);
3377 rc = mount_get_dfs_conns(mnt_ctx);
3380 if (cifs_is_referral_server(mnt_ctx->tcon, &ref))
3381 set_root_ses(mnt_ctx);
3382 rc = dfs_cache_update_tgthint(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3383 cifs_remap(cifs_sb), ref_path, tit);
3387 free_dfs_info_param(&ref);
3391 static int connect_dfs_root(struct mount_ctx *mnt_ctx, struct dfs_cache_tgt_list *root_tl)
3395 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3396 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3397 struct dfs_cache_tgt_iterator *tit;
3399 /* Put initial connections as they might be shared with other mounts. We need unique dfs
3400 * connections per mount to properly failover, so mount_get_dfs_conns() must be used from
3403 mount_put_conns(mnt_ctx);
3404 mount_get_dfs_conns(mnt_ctx);
3405 set_root_ses(mnt_ctx);
3407 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3408 if (IS_ERR(full_path))
3409 return PTR_ERR(full_path);
3411 mnt_ctx->origin_fullpath = dfs_cache_canonical_path(ctx->UNC, cifs_sb->local_nls,
3412 cifs_remap(cifs_sb));
3413 if (IS_ERR(mnt_ctx->origin_fullpath)) {
3414 rc = PTR_ERR(mnt_ctx->origin_fullpath);
3415 mnt_ctx->origin_fullpath = NULL;
3419 /* Try all dfs root targets */
3420 for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(root_tl);
3421 tit; tit = dfs_cache_get_next_tgt(root_tl, tit)) {
3422 rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->origin_fullpath + 1, tit);
3424 mnt_ctx->leaf_fullpath = kstrdup(mnt_ctx->origin_fullpath, GFP_KERNEL);
3425 if (!mnt_ctx->leaf_fullpath)
3436 static int __follow_dfs_link(struct mount_ctx *mnt_ctx)
3439 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3440 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3442 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3443 struct dfs_cache_tgt_iterator *tit;
3445 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3446 if (IS_ERR(full_path))
3447 return PTR_ERR(full_path);
3449 kfree(mnt_ctx->leaf_fullpath);
3450 mnt_ctx->leaf_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3451 cifs_remap(cifs_sb));
3452 if (IS_ERR(mnt_ctx->leaf_fullpath)) {
3453 rc = PTR_ERR(mnt_ctx->leaf_fullpath);
3454 mnt_ctx->leaf_fullpath = NULL;
3458 /* Get referral from dfs link */
3459 rc = dfs_cache_find(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3460 cifs_remap(cifs_sb), mnt_ctx->leaf_fullpath + 1, NULL, &tl);
3464 /* Try all dfs link targets */
3465 for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(&tl);
3466 tit; tit = dfs_cache_get_next_tgt(&tl, tit)) {
3467 rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->leaf_fullpath + 1, tit);
3469 rc = is_path_remote(mnt_ctx);
3476 dfs_cache_free_tgts(&tl);
3480 static int follow_dfs_link(struct mount_ctx *mnt_ctx)
3483 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3484 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3488 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3489 if (IS_ERR(full_path))
3490 return PTR_ERR(full_path);
3492 kfree(mnt_ctx->origin_fullpath);
3493 mnt_ctx->origin_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3494 cifs_remap(cifs_sb));
3497 if (IS_ERR(mnt_ctx->origin_fullpath)) {
3498 rc = PTR_ERR(mnt_ctx->origin_fullpath);
3499 mnt_ctx->origin_fullpath = NULL;
3504 rc = __follow_dfs_link(mnt_ctx);
3505 if (!rc || rc != -EREMOTE)
3507 } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
3512 /* Set up DFS referral paths for failover */
3513 static void setup_server_referral_paths(struct mount_ctx *mnt_ctx)
3515 struct TCP_Server_Info *server = mnt_ctx->server;
3517 server->origin_fullpath = mnt_ctx->origin_fullpath;
3518 server->leaf_fullpath = mnt_ctx->leaf_fullpath;
3519 server->current_fullpath = mnt_ctx->leaf_fullpath;
3520 mnt_ctx->origin_fullpath = mnt_ctx->leaf_fullpath = NULL;
3523 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3526 struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3527 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3530 rc = is_dfs_mount(&mnt_ctx, &isdfs, &tl);
3536 uuid_gen(&mnt_ctx.mount_id);
3537 rc = connect_dfs_root(&mnt_ctx, &tl);
3538 dfs_cache_free_tgts(&tl);
3543 rc = is_path_remote(&mnt_ctx);
3545 rc = follow_dfs_link(&mnt_ctx);
3549 setup_server_referral_paths(&mnt_ctx);
3551 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3552 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3554 cifs_autodisable_serverino(cifs_sb);
3556 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3557 * that have different prefix paths.
3559 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3560 kfree(cifs_sb->prepath);
3561 cifs_sb->prepath = ctx->prepath;
3562 ctx->prepath = NULL;
3563 uuid_copy(&cifs_sb->dfs_mount_id, &mnt_ctx.mount_id);
3566 cifs_try_adding_channels(cifs_sb, mnt_ctx.ses);
3567 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3571 free_xid(mnt_ctx.xid);
3575 dfs_cache_put_refsrv_sessions(&mnt_ctx.mount_id);
3576 kfree(mnt_ctx.origin_fullpath);
3577 kfree(mnt_ctx.leaf_fullpath);
3578 mount_put_conns(&mnt_ctx);
3582 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3585 struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3587 rc = mount_get_conns(&mnt_ctx);
3592 rc = is_path_remote(&mnt_ctx);
3599 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3603 free_xid(mnt_ctx.xid);
3607 mount_put_conns(&mnt_ctx);
3613 * Issue a TREE_CONNECT request.
3616 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3617 const char *tree, struct cifs_tcon *tcon,
3618 const struct nls_table *nls_codepage)
3620 struct smb_hdr *smb_buffer;
3621 struct smb_hdr *smb_buffer_response;
3624 unsigned char *bcc_ptr;
3627 __u16 bytes_left, count;
3632 smb_buffer = cifs_buf_get();
3633 if (smb_buffer == NULL)
3636 smb_buffer_response = smb_buffer;
3638 header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3639 NULL /*no tid */ , 4 /*wct */ );
3641 smb_buffer->Mid = get_next_mid(ses->server);
3642 smb_buffer->Uid = ses->Suid;
3643 pSMB = (TCONX_REQ *) smb_buffer;
3644 pSMBr = (TCONX_RSP *) smb_buffer_response;
3646 pSMB->AndXCommand = 0xFF;
3647 pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3648 bcc_ptr = &pSMB->Password[0];
3650 pSMB->PasswordLength = cpu_to_le16(1); /* minimum */
3651 *bcc_ptr = 0; /* password is null byte */
3652 bcc_ptr++; /* skip password */
3653 /* already aligned so no need to do it below */
3655 if (ses->server->sign)
3656 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3658 if (ses->capabilities & CAP_STATUS32) {
3659 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3661 if (ses->capabilities & CAP_DFS) {
3662 smb_buffer->Flags2 |= SMBFLG2_DFS;
3664 if (ses->capabilities & CAP_UNICODE) {
3665 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3667 cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3668 6 /* max utf8 char length in bytes */ *
3669 (/* server len*/ + 256 /* share len */), nls_codepage);
3670 bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */
3671 bcc_ptr += 2; /* skip trailing null */
3672 } else { /* ASCII */
3673 strcpy(bcc_ptr, tree);
3674 bcc_ptr += strlen(tree) + 1;
3676 strcpy(bcc_ptr, "?????");
3677 bcc_ptr += strlen("?????");
3679 count = bcc_ptr - &pSMB->Password[0];
3680 be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3681 pSMB->ByteCount = cpu_to_le16(count);
3683 rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3686 /* above now done in SendReceive */
3690 tcon->tidStatus = CifsGood;
3691 tcon->need_reconnect = false;
3692 tcon->tid = smb_buffer_response->Tid;
3693 bcc_ptr = pByteArea(smb_buffer_response);
3694 bytes_left = get_bcc(smb_buffer_response);
3695 length = strnlen(bcc_ptr, bytes_left - 2);
3696 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3702 /* skip service field (NB: this field is always ASCII) */
3704 if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3705 (bcc_ptr[2] == 'C')) {
3706 cifs_dbg(FYI, "IPC connection\n");
3710 } else if (length == 2) {
3711 if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3712 /* the most common case */
3713 cifs_dbg(FYI, "disk share connection\n");
3716 bcc_ptr += length + 1;
3717 bytes_left -= (length + 1);
3718 strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
3720 /* mostly informational -- no need to fail on error here */
3721 kfree(tcon->nativeFileSystem);
3722 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3723 bytes_left, is_unicode,
3726 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3728 if ((smb_buffer_response->WordCount == 3) ||
3729 (smb_buffer_response->WordCount == 7))
3730 /* field is in same location */
3731 tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3734 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3737 cifs_buf_release(smb_buffer);
3741 static void delayed_free(struct rcu_head *p)
3743 struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
3745 unload_nls(cifs_sb->local_nls);
3746 smb3_cleanup_fs_context(cifs_sb->ctx);
3751 cifs_umount(struct cifs_sb_info *cifs_sb)
3753 struct rb_root *root = &cifs_sb->tlink_tree;
3754 struct rb_node *node;
3755 struct tcon_link *tlink;
3757 cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3759 spin_lock(&cifs_sb->tlink_tree_lock);
3760 while ((node = rb_first(root))) {
3761 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3762 cifs_get_tlink(tlink);
3763 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3764 rb_erase(node, root);
3766 spin_unlock(&cifs_sb->tlink_tree_lock);
3767 cifs_put_tlink(tlink);
3768 spin_lock(&cifs_sb->tlink_tree_lock);
3770 spin_unlock(&cifs_sb->tlink_tree_lock);
3772 kfree(cifs_sb->prepath);
3773 #ifdef CONFIG_CIFS_DFS_UPCALL
3774 dfs_cache_put_refsrv_sessions(&cifs_sb->dfs_mount_id);
3776 call_rcu(&cifs_sb->rcu, delayed_free);
3780 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses)
3783 struct TCP_Server_Info *server = cifs_ses_server(ses);
3785 if (!server->ops->need_neg || !server->ops->negotiate)
3788 /* only send once per connect */
3789 if (!server->ops->need_neg(server))
3792 rc = server->ops->negotiate(xid, ses);
3794 spin_lock(&GlobalMid_Lock);
3795 if (server->tcpStatus == CifsNeedNegotiate)
3796 server->tcpStatus = CifsGood;
3799 spin_unlock(&GlobalMid_Lock);
3806 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
3807 struct nls_table *nls_info)
3810 struct TCP_Server_Info *server = cifs_ses_server(ses);
3812 if (!ses->binding) {
3813 ses->capabilities = server->capabilities;
3814 if (!linuxExtEnabled)
3815 ses->capabilities &= (~server->vals->cap_unix);
3817 if (ses->auth_key.response) {
3818 cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
3819 ses->auth_key.response);
3820 kfree(ses->auth_key.response);
3821 ses->auth_key.response = NULL;
3822 ses->auth_key.len = 0;
3826 cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
3827 server->sec_mode, server->capabilities, server->timeAdj);
3829 if (server->ops->sess_setup)
3830 rc = server->ops->sess_setup(xid, ses, nls_info);
3833 cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
3839 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
3841 ctx->sectype = ses->sectype;
3843 /* krb5 is special, since we don't need username or pw */
3844 if (ctx->sectype == Kerberos)
3847 return cifs_set_cifscreds(ctx, ses);
3850 static struct cifs_tcon *
3851 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
3854 struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
3855 struct cifs_ses *ses;
3856 struct cifs_tcon *tcon = NULL;
3857 struct smb3_fs_context *ctx;
3859 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3861 return ERR_PTR(-ENOMEM);
3863 ctx->local_nls = cifs_sb->local_nls;
3864 ctx->linux_uid = fsuid;
3865 ctx->cred_uid = fsuid;
3866 ctx->UNC = master_tcon->treeName;
3867 ctx->retry = master_tcon->retry;
3868 ctx->nocase = master_tcon->nocase;
3869 ctx->nohandlecache = master_tcon->nohandlecache;
3870 ctx->local_lease = master_tcon->local_lease;
3871 ctx->no_lease = master_tcon->no_lease;
3872 ctx->resilient = master_tcon->use_resilient;
3873 ctx->persistent = master_tcon->use_persistent;
3874 ctx->handle_timeout = master_tcon->handle_timeout;
3875 ctx->no_linux_ext = !master_tcon->unix_ext;
3876 ctx->linux_ext = master_tcon->posix_extensions;
3877 ctx->sectype = master_tcon->ses->sectype;
3878 ctx->sign = master_tcon->ses->sign;
3879 ctx->seal = master_tcon->seal;
3880 ctx->witness = master_tcon->use_witness;
3882 rc = cifs_set_vol_auth(ctx, master_tcon->ses);
3888 /* get a reference for the same TCP session */
3889 spin_lock(&cifs_tcp_ses_lock);
3890 ++master_tcon->ses->server->srv_count;
3891 spin_unlock(&cifs_tcp_ses_lock);
3893 ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
3895 tcon = (struct cifs_tcon *)ses;
3896 cifs_put_tcp_session(master_tcon->ses->server, 0);
3900 tcon = cifs_get_tcon(ses, ctx);
3902 cifs_put_smb_ses(ses);
3907 reset_cifs_unix_caps(0, tcon, NULL, ctx);
3910 kfree(ctx->username);
3911 kfree_sensitive(ctx->password);
3918 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
3920 return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
3923 /* find and return a tlink with given uid */
3924 static struct tcon_link *
3925 tlink_rb_search(struct rb_root *root, kuid_t uid)
3927 struct rb_node *node = root->rb_node;
3928 struct tcon_link *tlink;
3931 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3933 if (uid_gt(tlink->tl_uid, uid))
3934 node = node->rb_left;
3935 else if (uid_lt(tlink->tl_uid, uid))
3936 node = node->rb_right;
3943 /* insert a tcon_link into the tree */
3945 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
3947 struct rb_node **new = &(root->rb_node), *parent = NULL;
3948 struct tcon_link *tlink;
3951 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
3954 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
3955 new = &((*new)->rb_left);
3957 new = &((*new)->rb_right);
3960 rb_link_node(&new_tlink->tl_rbnode, parent, new);
3961 rb_insert_color(&new_tlink->tl_rbnode, root);
3965 * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
3968 * If the superblock doesn't refer to a multiuser mount, then just return
3969 * the master tcon for the mount.
3971 * First, search the rbtree for an existing tcon for this fsuid. If one
3972 * exists, then check to see if it's pending construction. If it is then wait
3973 * for construction to complete. Once it's no longer pending, check to see if
3974 * it failed and either return an error or retry construction, depending on
3977 * If one doesn't exist then insert a new tcon_link struct into the tree and
3978 * try to construct a new one.
3981 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
3984 kuid_t fsuid = current_fsuid();
3985 struct tcon_link *tlink, *newtlink;
3987 if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
3988 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
3990 spin_lock(&cifs_sb->tlink_tree_lock);
3991 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
3993 cifs_get_tlink(tlink);
3994 spin_unlock(&cifs_sb->tlink_tree_lock);
3996 if (tlink == NULL) {
3997 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3998 if (newtlink == NULL)
3999 return ERR_PTR(-ENOMEM);
4000 newtlink->tl_uid = fsuid;
4001 newtlink->tl_tcon = ERR_PTR(-EACCES);
4002 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4003 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4004 cifs_get_tlink(newtlink);
4006 spin_lock(&cifs_sb->tlink_tree_lock);
4007 /* was one inserted after previous search? */
4008 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4010 cifs_get_tlink(tlink);
4011 spin_unlock(&cifs_sb->tlink_tree_lock);
4013 goto wait_for_construction;
4016 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4017 spin_unlock(&cifs_sb->tlink_tree_lock);
4019 wait_for_construction:
4020 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4021 TASK_INTERRUPTIBLE);
4023 cifs_put_tlink(tlink);
4024 return ERR_PTR(-ERESTARTSYS);
4027 /* if it's good, return it */
4028 if (!IS_ERR(tlink->tl_tcon))
4031 /* return error if we tried this already recently */
4032 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4033 cifs_put_tlink(tlink);
4034 return ERR_PTR(-EACCES);
4037 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4038 goto wait_for_construction;
4041 tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4042 clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4043 wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4045 if (IS_ERR(tlink->tl_tcon)) {
4046 cifs_put_tlink(tlink);
4047 return ERR_PTR(-EACCES);
4054 * periodic workqueue job that scans tcon_tree for a superblock and closes
4058 cifs_prune_tlinks(struct work_struct *work)
4060 struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4062 struct rb_root *root = &cifs_sb->tlink_tree;
4063 struct rb_node *node;
4064 struct rb_node *tmp;
4065 struct tcon_link *tlink;
4068 * Because we drop the spinlock in the loop in order to put the tlink
4069 * it's not guarded against removal of links from the tree. The only
4070 * places that remove entries from the tree are this function and
4071 * umounts. Because this function is non-reentrant and is canceled
4072 * before umount can proceed, this is safe.
4074 spin_lock(&cifs_sb->tlink_tree_lock);
4075 node = rb_first(root);
4076 while (node != NULL) {
4078 node = rb_next(tmp);
4079 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4081 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4082 atomic_read(&tlink->tl_count) != 0 ||
4083 time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4086 cifs_get_tlink(tlink);
4087 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4088 rb_erase(tmp, root);
4090 spin_unlock(&cifs_sb->tlink_tree_lock);
4091 cifs_put_tlink(tlink);
4092 spin_lock(&cifs_sb->tlink_tree_lock);
4094 spin_unlock(&cifs_sb->tlink_tree_lock);
4096 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4100 #ifdef CONFIG_CIFS_DFS_UPCALL
4101 static void mark_tcon_tcp_ses_for_reconnect(struct cifs_tcon *tcon)
4105 for (i = 0; i < tcon->ses->chan_count; i++) {
4106 spin_lock(&GlobalMid_Lock);
4107 if (tcon->ses->chans[i].server->tcpStatus != CifsExiting)
4108 tcon->ses->chans[i].server->tcpStatus = CifsNeedReconnect;
4109 spin_unlock(&GlobalMid_Lock);
4113 /* Update dfs referral path of superblock */
4114 static int update_server_fullpath(struct TCP_Server_Info *server, struct cifs_sb_info *cifs_sb,
4118 size_t len = strlen(target);
4119 char *refpath, *npath;
4121 if (unlikely(len < 2 || *target != '\\'))
4124 if (target[1] == '\\') {
4126 refpath = kmalloc(len, GFP_KERNEL);
4130 scnprintf(refpath, len, "%s", target);
4132 len += sizeof("\\");
4133 refpath = kmalloc(len, GFP_KERNEL);
4137 scnprintf(refpath, len, "\\%s", target);
4140 npath = dfs_cache_canonical_path(refpath, cifs_sb->local_nls, cifs_remap(cifs_sb));
4143 if (IS_ERR(npath)) {
4144 rc = PTR_ERR(npath);
4146 mutex_lock(&server->refpath_lock);
4147 kfree(server->leaf_fullpath);
4148 server->leaf_fullpath = npath;
4149 mutex_unlock(&server->refpath_lock);
4150 server->current_fullpath = server->leaf_fullpath;
4155 static int target_share_matches_server(struct TCP_Server_Info *server, const char *tcp_host,
4156 size_t tcp_host_len, char *share, bool *target_match)
4159 const char *dfs_host;
4160 size_t dfs_host_len;
4162 *target_match = true;
4163 extract_unc_hostname(share, &dfs_host, &dfs_host_len);
4165 /* Check if hostnames or addresses match */
4166 if (dfs_host_len != tcp_host_len || strncasecmp(dfs_host, tcp_host, dfs_host_len) != 0) {
4167 cifs_dbg(FYI, "%s: %.*s doesn't match %.*s\n", __func__, (int)dfs_host_len,
4168 dfs_host, (int)tcp_host_len, tcp_host);
4169 rc = match_target_ip(server, dfs_host, dfs_host_len, target_match);
4171 cifs_dbg(VFS, "%s: failed to match target ip: %d\n", __func__, rc);
4176 int __tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4177 struct cifs_sb_info *cifs_sb, char *tree,
4178 struct dfs_cache_tgt_list *tl, struct dfs_info3_param *ref)
4181 struct TCP_Server_Info *server = tcon->ses->server;
4182 const struct smb_version_operations *ops = server->ops;
4183 struct cifs_tcon *ipc = tcon->ses->tcon_ipc;
4185 char *share = NULL, *prefix = NULL;
4186 const char *tcp_host;
4187 size_t tcp_host_len;
4188 struct dfs_cache_tgt_iterator *tit;
4191 extract_unc_hostname(server->hostname, &tcp_host, &tcp_host_len);
4193 islink = ref->server_type == DFS_TYPE_LINK;
4194 free_dfs_info_param(ref);
4196 tit = dfs_cache_get_tgt_iterator(tl);
4202 /* Try to tree connect to all dfs targets */
4203 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
4204 const char *target = dfs_cache_get_tgt_name(tit);
4205 struct dfs_cache_tgt_list ntl = DFS_CACHE_TGT_LIST_INIT(ntl);
4210 /* Check if share matches with tcp ses */
4211 rc = dfs_cache_get_tgt_share(server->current_fullpath + 1, tit, &share, &prefix);
4213 cifs_dbg(VFS, "%s: failed to parse target share: %d\n", __func__, rc);
4217 rc = target_share_matches_server(server, tcp_host, tcp_host_len, share,
4221 if (!target_match) {
4226 if (ipc->need_reconnect) {
4227 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4228 rc = ops->tree_connect(xid, ipc->ses, tree, ipc, cifs_sb->local_nls);
4233 scnprintf(tree, MAX_TREE_SIZE, "\\%s", share);
4235 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4239 * If no dfs referrals were returned from link target, then just do a TREE_CONNECT
4240 * to it. Otherwise, cache the dfs referral and then mark current tcp ses for
4241 * reconnect so either the demultiplex thread or the echo worker will reconnect to
4242 * newly resolved target.
4244 if (dfs_cache_find(xid, tcon->ses, cifs_sb->local_nls, cifs_remap(cifs_sb), target,
4246 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4249 rc = dfs_cache_noreq_update_tgthint(server->current_fullpath + 1, tit);
4251 rc = cifs_update_super_prepath(cifs_sb, prefix);
4254 /* Target is another dfs share */
4255 rc = update_server_fullpath(server, cifs_sb, target);
4256 dfs_cache_free_tgts(tl);
4260 list_replace_init(&ntl.tl_list, &tl->tl_list);
4262 dfs_cache_free_tgts(&ntl);
4263 free_dfs_info_param(ref);
4275 int tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4276 struct cifs_sb_info *cifs_sb, char *tree,
4277 struct dfs_cache_tgt_list *tl, struct dfs_info3_param *ref)
4281 struct TCP_Server_Info *server = tcon->ses->server;
4284 rc = __tree_connect_dfs_target(xid, tcon, cifs_sb, tree, tl, ref);
4285 if (!rc || rc != -EREMOTE)
4287 } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
4289 * If we couldn't tree connect to any targets from last referral path, then retry from
4290 * original referral path.
4292 if (rc && server->current_fullpath != server->origin_fullpath) {
4293 server->current_fullpath = server->origin_fullpath;
4294 mark_tcon_tcp_ses_for_reconnect(tcon);
4297 dfs_cache_free_tgts(tl);
4301 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4304 struct TCP_Server_Info *server = tcon->ses->server;
4305 const struct smb_version_operations *ops = server->ops;
4306 struct super_block *sb = NULL;
4307 struct cifs_sb_info *cifs_sb;
4308 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
4310 struct dfs_info3_param ref = {0};
4312 tree = kzalloc(MAX_TREE_SIZE, GFP_KERNEL);
4317 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4318 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, nlsc);
4322 sb = cifs_get_tcp_super(server);
4325 cifs_dbg(VFS, "%s: could not find superblock: %d\n", __func__, rc);
4329 cifs_sb = CIFS_SB(sb);
4331 /* If it is not dfs or there was no cached dfs referral, then reconnect to same share */
4332 if (!server->current_fullpath ||
4333 dfs_cache_noreq_find(server->current_fullpath + 1, &ref, &tl)) {
4334 rc = ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, cifs_sb->local_nls);
4338 rc = tree_connect_dfs_target(xid, tcon, cifs_sb, tree, &tl, &ref);
4342 cifs_put_tcp_super(sb);
4347 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4349 const struct smb_version_operations *ops = tcon->ses->server->ops;
4351 return ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, nlsc);