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 MAX_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 /* if server hostname isn't populated, there's nothing to do here */
101 if (server->hostname[0] == '\0')
104 len = strlen(server->hostname) + 3;
106 unc = kmalloc(len, GFP_KERNEL);
108 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
111 scnprintf(unc, len, "\\\\%s", server->hostname);
113 rc = dns_resolve_server_name_to_ip(unc, &ipaddr, &expiry);
117 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
118 __func__, server->hostname, rc);
119 goto requeue_resolve;
122 spin_lock(&server->srv_lock);
123 rc = cifs_convert_address((struct sockaddr *)&server->dstaddr, ipaddr,
125 spin_unlock(&server->srv_lock);
128 /* rc == 1 means success here */
130 now = ktime_get_real_seconds();
131 if (expiry && expiry > now)
133 * To make sure we don't use the cached entry, retry 1s
136 ttl = max_t(unsigned long, expiry - now, SMB_DNS_RESOLVE_INTERVAL_MIN) + 1;
141 cifs_dbg(FYI, "%s: next dns resolution scheduled for %lu seconds in the future\n",
143 mod_delayed_work(cifsiod_wq, &server->resolve, (ttl * HZ));
148 static void smb2_query_server_interfaces(struct work_struct *work)
151 struct cifs_tcon *tcon = container_of(work,
153 query_interfaces.work);
156 * query server network interfaces, in case they change
158 rc = SMB3_request_interfaces(0, tcon, false);
160 cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
164 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
165 (SMB_INTERFACE_POLL_INTERVAL * HZ));
168 static void cifs_resolve_server(struct work_struct *work)
171 struct TCP_Server_Info *server = container_of(work,
172 struct TCP_Server_Info, resolve.work);
174 cifs_server_lock(server);
177 * Resolve the hostname again to make sure that IP address is up-to-date.
179 rc = reconn_set_ipaddr_from_hostname(server);
181 cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
185 cifs_server_unlock(server);
189 * Update the tcpStatus for the server.
190 * This is used to signal the cifsd thread to call cifs_reconnect
191 * ONLY cifsd thread should call cifs_reconnect. For any other
192 * thread, use this function
194 * @server: the tcp ses for which reconnect is needed
195 * @all_channels: if this needs to be done for all channels
198 cifs_signal_cifsd_for_reconnect(struct TCP_Server_Info *server,
201 struct TCP_Server_Info *pserver;
202 struct cifs_ses *ses;
205 /* If server is a channel, select the primary channel */
206 pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
208 /* if we need to signal just this channel */
210 spin_lock(&server->srv_lock);
211 if (server->tcpStatus != CifsExiting)
212 server->tcpStatus = CifsNeedReconnect;
213 spin_unlock(&server->srv_lock);
217 spin_lock(&cifs_tcp_ses_lock);
218 list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
219 if (cifs_ses_exiting(ses))
221 spin_lock(&ses->chan_lock);
222 for (i = 0; i < ses->chan_count; i++) {
223 spin_lock(&ses->chans[i].server->srv_lock);
224 ses->chans[i].server->tcpStatus = CifsNeedReconnect;
225 spin_unlock(&ses->chans[i].server->srv_lock);
227 spin_unlock(&ses->chan_lock);
229 spin_unlock(&cifs_tcp_ses_lock);
233 * Mark all sessions and tcons for reconnect.
234 * IMPORTANT: make sure that this gets called only from
235 * cifsd thread. For any other thread, use
236 * cifs_signal_cifsd_for_reconnect
238 * @server: the tcp ses for which reconnect is needed
239 * @server needs to be previously set to CifsNeedReconnect.
240 * @mark_smb_session: whether even sessions need to be marked
243 cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server,
244 bool mark_smb_session)
246 struct TCP_Server_Info *pserver;
247 struct cifs_ses *ses, *nses;
248 struct cifs_tcon *tcon;
251 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
252 * are not used until reconnected.
254 cifs_dbg(FYI, "%s: marking necessary sessions and tcons for reconnect\n", __func__);
256 /* If server is a channel, select the primary channel */
257 pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
260 spin_lock(&cifs_tcp_ses_lock);
261 list_for_each_entry_safe(ses, nses, &pserver->smb_ses_list, smb_ses_list) {
262 /* check if iface is still active */
263 spin_lock(&ses->chan_lock);
264 if (!cifs_chan_is_iface_active(ses, server)) {
265 spin_unlock(&ses->chan_lock);
266 cifs_chan_update_iface(ses, server);
267 spin_lock(&ses->chan_lock);
270 if (!mark_smb_session && cifs_chan_needs_reconnect(ses, server)) {
271 spin_unlock(&ses->chan_lock);
275 if (mark_smb_session)
276 CIFS_SET_ALL_CHANS_NEED_RECONNECT(ses);
278 cifs_chan_set_need_reconnect(ses, server);
280 cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
281 __func__, ses->chans_need_reconnect);
283 /* If all channels need reconnect, then tcon needs reconnect */
284 if (!mark_smb_session && !CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
285 spin_unlock(&ses->chan_lock);
288 spin_unlock(&ses->chan_lock);
290 spin_lock(&ses->ses_lock);
291 ses->ses_status = SES_NEED_RECON;
292 spin_unlock(&ses->ses_lock);
294 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
295 tcon->need_reconnect = true;
296 spin_lock(&tcon->tc_lock);
297 tcon->status = TID_NEED_RECON;
298 spin_unlock(&tcon->tc_lock);
301 ses->tcon_ipc->need_reconnect = true;
302 spin_lock(&ses->tcon_ipc->tc_lock);
303 ses->tcon_ipc->status = TID_NEED_RECON;
304 spin_unlock(&ses->tcon_ipc->tc_lock);
307 spin_unlock(&cifs_tcp_ses_lock);
311 cifs_abort_connection(struct TCP_Server_Info *server)
313 struct mid_q_entry *mid, *nmid;
314 struct list_head retry_list;
317 server->max_read = 0;
319 /* do not want to be sending data on a socket we are freeing */
320 cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
321 cifs_server_lock(server);
322 if (server->ssocket) {
323 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
324 server->ssocket->flags);
325 kernel_sock_shutdown(server->ssocket, SHUT_WR);
326 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
327 server->ssocket->flags);
328 sock_release(server->ssocket);
329 server->ssocket = NULL;
331 server->sequence_number = 0;
332 server->session_estab = false;
333 kfree_sensitive(server->session_key.response);
334 server->session_key.response = NULL;
335 server->session_key.len = 0;
336 server->lstrp = jiffies;
338 /* mark submitted MIDs for retry and issue callback */
339 INIT_LIST_HEAD(&retry_list);
340 cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
341 spin_lock(&server->mid_lock);
342 list_for_each_entry_safe(mid, nmid, &server->pending_mid_q, qhead) {
343 kref_get(&mid->refcount);
344 if (mid->mid_state == MID_REQUEST_SUBMITTED)
345 mid->mid_state = MID_RETRY_NEEDED;
346 list_move(&mid->qhead, &retry_list);
347 mid->mid_flags |= MID_DELETED;
349 spin_unlock(&server->mid_lock);
350 cifs_server_unlock(server);
352 cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
353 list_for_each_entry_safe(mid, nmid, &retry_list, qhead) {
354 list_del_init(&mid->qhead);
359 if (cifs_rdma_enabled(server)) {
360 cifs_server_lock(server);
361 smbd_destroy(server);
362 cifs_server_unlock(server);
366 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
368 spin_lock(&server->srv_lock);
369 server->nr_targets = num_targets;
370 if (server->tcpStatus == CifsExiting) {
371 /* the demux thread will exit normally next time through the loop */
372 spin_unlock(&server->srv_lock);
373 wake_up(&server->response_q);
377 cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
378 trace_smb3_reconnect(server->CurrentMid, server->conn_id,
380 server->tcpStatus = CifsNeedReconnect;
382 spin_unlock(&server->srv_lock);
387 * cifs tcp session reconnection
389 * mark tcp session as reconnecting so temporarily locked
390 * mark all smb sessions as reconnecting for tcp session
391 * reconnect tcp session
392 * wake up waiters on reconnection? - (not needed currently)
394 * if mark_smb_session is passed as true, unconditionally mark
395 * the smb session (and tcon) for reconnect as well. This value
396 * doesn't really matter for non-multichannel scenario.
399 static int __cifs_reconnect(struct TCP_Server_Info *server,
400 bool mark_smb_session)
404 if (!cifs_tcp_ses_needs_reconnect(server, 1))
407 cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
409 cifs_abort_connection(server);
413 cifs_server_lock(server);
415 if (!cifs_swn_set_server_dstaddr(server)) {
416 /* resolve the hostname again to make sure that IP address is up-to-date */
417 rc = reconn_set_ipaddr_from_hostname(server);
418 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
421 if (cifs_rdma_enabled(server))
422 rc = smbd_reconnect(server);
424 rc = generic_ip_connect(server);
426 cifs_server_unlock(server);
427 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
430 atomic_inc(&tcpSesReconnectCount);
431 set_credits(server, 1);
432 spin_lock(&server->srv_lock);
433 if (server->tcpStatus != CifsExiting)
434 server->tcpStatus = CifsNeedNegotiate;
435 spin_unlock(&server->srv_lock);
436 cifs_swn_reset_server_dstaddr(server);
437 cifs_server_unlock(server);
438 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
440 } while (server->tcpStatus == CifsNeedReconnect);
442 spin_lock(&server->srv_lock);
443 if (server->tcpStatus == CifsNeedNegotiate)
444 mod_delayed_work(cifsiod_wq, &server->echo, 0);
445 spin_unlock(&server->srv_lock);
447 wake_up(&server->response_q);
451 #ifdef CONFIG_CIFS_DFS_UPCALL
452 static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
457 if (!cifs_swn_set_server_dstaddr(server)) {
458 if (server->hostname != target) {
459 hostname = extract_hostname(target);
460 if (!IS_ERR(hostname)) {
461 spin_lock(&server->srv_lock);
462 kfree(server->hostname);
463 server->hostname = hostname;
464 spin_unlock(&server->srv_lock);
466 cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
467 __func__, PTR_ERR(hostname));
468 cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
472 /* resolve the hostname again to make sure that IP address is up-to-date. */
473 rc = reconn_set_ipaddr_from_hostname(server);
474 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
476 /* Reconnect the socket */
477 if (cifs_rdma_enabled(server))
478 rc = smbd_reconnect(server);
480 rc = generic_ip_connect(server);
485 static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
486 struct dfs_cache_tgt_iterator **target_hint)
489 struct dfs_cache_tgt_iterator *tit;
493 /* If dfs target list is empty, then reconnect to last server */
494 tit = dfs_cache_get_tgt_iterator(tl);
496 return __reconnect_target_unlocked(server, server->hostname);
498 /* Otherwise, try every dfs target in @tl */
499 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
500 rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
509 static int reconnect_dfs_server(struct TCP_Server_Info *server)
512 const char *refpath = server->current_fullpath + 1;
513 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
514 struct dfs_cache_tgt_iterator *target_hint = NULL;
518 * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
520 * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
521 * targets (server->nr_targets). It's also possible that the cached referral was cleared
522 * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
523 * refreshing the referral, so, in this case, default it to 1.
525 if (!dfs_cache_noreq_find(refpath, NULL, &tl))
526 num_targets = dfs_cache_get_nr_tgts(&tl);
530 if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
534 * Unconditionally mark all sessions & tcons for reconnect as we might be connecting to a
535 * different server or share during failover. It could be improved by adding some logic to
536 * only do that in case it connects to a different server or share, though.
538 cifs_mark_tcp_ses_conns_for_reconnect(server, true);
540 cifs_abort_connection(server);
544 cifs_server_lock(server);
546 rc = reconnect_target_unlocked(server, &tl, &target_hint);
548 /* Failed to reconnect socket */
549 cifs_server_unlock(server);
550 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
555 * Socket was created. Update tcp session status to CifsNeedNegotiate so that a
556 * process waiting for reconnect will know it needs to re-establish session and tcon
557 * through the reconnected target server.
559 atomic_inc(&tcpSesReconnectCount);
560 set_credits(server, 1);
561 spin_lock(&server->srv_lock);
562 if (server->tcpStatus != CifsExiting)
563 server->tcpStatus = CifsNeedNegotiate;
564 spin_unlock(&server->srv_lock);
565 cifs_swn_reset_server_dstaddr(server);
566 cifs_server_unlock(server);
567 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
568 } while (server->tcpStatus == CifsNeedReconnect);
571 dfs_cache_noreq_update_tgthint(refpath, target_hint);
573 dfs_cache_free_tgts(&tl);
575 /* Need to set up echo worker again once connection has been established */
576 spin_lock(&server->srv_lock);
577 if (server->tcpStatus == CifsNeedNegotiate)
578 mod_delayed_work(cifsiod_wq, &server->echo, 0);
579 spin_unlock(&server->srv_lock);
581 wake_up(&server->response_q);
585 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
587 /* If tcp session is not an dfs connection, then reconnect to last target server */
588 spin_lock(&server->srv_lock);
589 if (!server->is_dfs_conn) {
590 spin_unlock(&server->srv_lock);
591 return __cifs_reconnect(server, mark_smb_session);
593 spin_unlock(&server->srv_lock);
595 mutex_lock(&server->refpath_lock);
596 if (!server->origin_fullpath || !server->leaf_fullpath) {
597 mutex_unlock(&server->refpath_lock);
598 return __cifs_reconnect(server, mark_smb_session);
600 mutex_unlock(&server->refpath_lock);
602 return reconnect_dfs_server(server);
605 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
607 return __cifs_reconnect(server, mark_smb_session);
612 cifs_echo_request(struct work_struct *work)
615 struct TCP_Server_Info *server = container_of(work,
616 struct TCP_Server_Info, echo.work);
619 * We cannot send an echo if it is disabled.
620 * Also, no need to ping if we got a response recently.
623 if (server->tcpStatus == CifsNeedReconnect ||
624 server->tcpStatus == CifsExiting ||
625 server->tcpStatus == CifsNew ||
626 (server->ops->can_echo && !server->ops->can_echo(server)) ||
627 time_before(jiffies, server->lstrp + server->echo_interval - HZ))
630 rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
631 cifs_server_dbg(FYI, "send echo request: rc = %d\n", rc);
633 /* Check witness registrations */
637 queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
641 allocate_buffers(struct TCP_Server_Info *server)
643 if (!server->bigbuf) {
644 server->bigbuf = (char *)cifs_buf_get();
645 if (!server->bigbuf) {
646 cifs_server_dbg(VFS, "No memory for large SMB response\n");
648 /* retry will check if exiting */
651 } else if (server->large_buf) {
652 /* we are reusing a dirty large buf, clear its start */
653 memset(server->bigbuf, 0, HEADER_SIZE(server));
656 if (!server->smallbuf) {
657 server->smallbuf = (char *)cifs_small_buf_get();
658 if (!server->smallbuf) {
659 cifs_server_dbg(VFS, "No memory for SMB response\n");
661 /* retry will check if exiting */
664 /* beginning of smb buffer is cleared in our buf_get */
666 /* if existing small buf clear beginning */
667 memset(server->smallbuf, 0, HEADER_SIZE(server));
674 server_unresponsive(struct TCP_Server_Info *server)
677 * We need to wait 3 echo intervals to make sure we handle such
679 * 1s client sends a normal SMB request
680 * 2s client gets a response
681 * 30s echo workqueue job pops, and decides we got a response recently
682 * and don't need to send another
684 * 65s kernel_recvmsg times out, and we see that we haven't gotten
685 * a response in >60s.
687 spin_lock(&server->srv_lock);
688 if ((server->tcpStatus == CifsGood ||
689 server->tcpStatus == CifsNeedNegotiate) &&
690 (!server->ops->can_echo || server->ops->can_echo(server)) &&
691 time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
692 spin_unlock(&server->srv_lock);
693 cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
694 (3 * server->echo_interval) / HZ);
695 cifs_reconnect(server, false);
698 spin_unlock(&server->srv_lock);
704 zero_credits(struct TCP_Server_Info *server)
708 spin_lock(&server->req_lock);
709 val = server->credits + server->echo_credits + server->oplock_credits;
710 if (server->in_flight == 0 && val == 0) {
711 spin_unlock(&server->req_lock);
714 spin_unlock(&server->req_lock);
719 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
724 for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
727 /* reconnect if no credits and no requests in flight */
728 if (zero_credits(server)) {
729 cifs_reconnect(server, false);
730 return -ECONNABORTED;
733 if (server_unresponsive(server))
734 return -ECONNABORTED;
735 if (cifs_rdma_enabled(server) && server->smbd_conn)
736 length = smbd_recv(server->smbd_conn, smb_msg);
738 length = sock_recvmsg(server->ssocket, smb_msg, 0);
740 spin_lock(&server->srv_lock);
741 if (server->tcpStatus == CifsExiting) {
742 spin_unlock(&server->srv_lock);
746 if (server->tcpStatus == CifsNeedReconnect) {
747 spin_unlock(&server->srv_lock);
748 cifs_reconnect(server, false);
749 return -ECONNABORTED;
751 spin_unlock(&server->srv_lock);
753 if (length == -ERESTARTSYS ||
757 * Minimum sleep to prevent looping, allowing socket
758 * to clear and app threads to set tcpStatus
759 * CifsNeedReconnect if server hung.
761 usleep_range(1000, 2000);
767 cifs_dbg(FYI, "Received no data or error: %d\n", length);
768 cifs_reconnect(server, false);
769 return -ECONNABORTED;
776 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
777 unsigned int to_read)
779 struct msghdr smb_msg = {};
780 struct kvec iov = {.iov_base = buf, .iov_len = to_read};
781 iov_iter_kvec(&smb_msg.msg_iter, ITER_DEST, &iov, 1, to_read);
783 return cifs_readv_from_socket(server, &smb_msg);
787 cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
789 struct msghdr smb_msg = {};
792 * iov_iter_discard already sets smb_msg.type and count and iov_offset
793 * and cifs_readv_from_socket sets msg_control and msg_controllen
794 * so little to initialize in struct msghdr
796 iov_iter_discard(&smb_msg.msg_iter, ITER_DEST, to_read);
798 return cifs_readv_from_socket(server, &smb_msg);
802 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
803 unsigned int page_offset, unsigned int to_read)
805 struct msghdr smb_msg = {};
806 struct bio_vec bv = {
807 .bv_page = page, .bv_len = to_read, .bv_offset = page_offset};
808 iov_iter_bvec(&smb_msg.msg_iter, ITER_DEST, &bv, 1, to_read);
809 return cifs_readv_from_socket(server, &smb_msg);
813 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
816 * The first byte big endian of the length field,
817 * is actually not part of the length but the type
818 * with the most common, zero, as regular data.
821 case RFC1002_SESSION_MESSAGE:
822 /* Regular SMB response */
824 case RFC1002_SESSION_KEEP_ALIVE:
825 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
827 case RFC1002_POSITIVE_SESSION_RESPONSE:
828 cifs_dbg(FYI, "RFC 1002 positive session response\n");
830 case RFC1002_NEGATIVE_SESSION_RESPONSE:
832 * We get this from Windows 98 instead of an error on
833 * SMB negprot response.
835 cifs_dbg(FYI, "RFC 1002 negative session response\n");
836 /* give server a second to clean up */
839 * Always try 445 first on reconnect since we get NACK
840 * on some if we ever connected to port 139 (the NACK
841 * is since we do not begin with RFC1001 session
844 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
845 cifs_reconnect(server, true);
848 cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
849 cifs_reconnect(server, true);
856 dequeue_mid(struct mid_q_entry *mid, bool malformed)
858 #ifdef CONFIG_CIFS_STATS2
859 mid->when_received = jiffies;
861 spin_lock(&mid->server->mid_lock);
863 mid->mid_state = MID_RESPONSE_RECEIVED;
865 mid->mid_state = MID_RESPONSE_MALFORMED;
867 * Trying to handle/dequeue a mid after the send_recv()
868 * function has finished processing it is a bug.
870 if (mid->mid_flags & MID_DELETED) {
871 spin_unlock(&mid->server->mid_lock);
872 pr_warn_once("trying to dequeue a deleted mid\n");
874 list_del_init(&mid->qhead);
875 mid->mid_flags |= MID_DELETED;
876 spin_unlock(&mid->server->mid_lock);
881 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
883 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
886 * SMB1 does not use credits.
891 return le16_to_cpu(shdr->CreditRequest);
895 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
896 char *buf, int malformed)
898 if (server->ops->check_trans2 &&
899 server->ops->check_trans2(mid, server, buf, malformed))
901 mid->credits_received = smb2_get_credits_from_hdr(buf, server);
903 mid->large_buf = server->large_buf;
904 /* Was previous buf put in mpx struct for multi-rsp? */
905 if (!mid->multiRsp) {
906 /* smb buffer will be freed by user thread */
907 if (server->large_buf)
908 server->bigbuf = NULL;
910 server->smallbuf = NULL;
912 dequeue_mid(mid, malformed);
916 cifs_enable_signing(struct TCP_Server_Info *server, bool mnt_sign_required)
918 bool srv_sign_required = server->sec_mode & server->vals->signing_required;
919 bool srv_sign_enabled = server->sec_mode & server->vals->signing_enabled;
920 bool mnt_sign_enabled;
923 * Is signing required by mnt options? If not then check
924 * global_secflags to see if it is there.
926 if (!mnt_sign_required)
927 mnt_sign_required = ((global_secflags & CIFSSEC_MUST_SIGN) ==
931 * If signing is required then it's automatically enabled too,
932 * otherwise, check to see if the secflags allow it.
934 mnt_sign_enabled = mnt_sign_required ? mnt_sign_required :
935 (global_secflags & CIFSSEC_MAY_SIGN);
937 /* If server requires signing, does client allow it? */
938 if (srv_sign_required) {
939 if (!mnt_sign_enabled) {
940 cifs_dbg(VFS, "Server requires signing, but it's disabled in SecurityFlags!\n");
946 /* If client requires signing, does server allow it? */
947 if (mnt_sign_required) {
948 if (!srv_sign_enabled) {
949 cifs_dbg(VFS, "Server does not support signing!\n");
955 if (cifs_rdma_enabled(server) && server->sign)
956 cifs_dbg(VFS, "Signing is enabled, and RDMA read/write will be disabled\n");
962 static void clean_demultiplex_info(struct TCP_Server_Info *server)
966 /* take it off the list, if it's not already */
967 spin_lock(&server->srv_lock);
968 list_del_init(&server->tcp_ses_list);
969 spin_unlock(&server->srv_lock);
971 cancel_delayed_work_sync(&server->echo);
972 cancel_delayed_work_sync(&server->resolve);
974 spin_lock(&server->srv_lock);
975 server->tcpStatus = CifsExiting;
976 spin_unlock(&server->srv_lock);
977 wake_up_all(&server->response_q);
979 /* check if we have blocked requests that need to free */
980 spin_lock(&server->req_lock);
981 if (server->credits <= 0)
983 spin_unlock(&server->req_lock);
985 * Although there should not be any requests blocked on this queue it
986 * can not hurt to be paranoid and try to wake up requests that may
987 * haven been blocked when more than 50 at time were on the wire to the
988 * same server - they now will see the session is in exit state and get
989 * out of SendReceive.
991 wake_up_all(&server->request_q);
992 /* give those requests time to exit */
994 if (cifs_rdma_enabled(server))
995 smbd_destroy(server);
996 if (server->ssocket) {
997 sock_release(server->ssocket);
998 server->ssocket = NULL;
1001 if (!list_empty(&server->pending_mid_q)) {
1002 struct list_head dispose_list;
1003 struct mid_q_entry *mid_entry;
1004 struct list_head *tmp, *tmp2;
1006 INIT_LIST_HEAD(&dispose_list);
1007 spin_lock(&server->mid_lock);
1008 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
1009 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
1010 cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
1011 kref_get(&mid_entry->refcount);
1012 mid_entry->mid_state = MID_SHUTDOWN;
1013 list_move(&mid_entry->qhead, &dispose_list);
1014 mid_entry->mid_flags |= MID_DELETED;
1016 spin_unlock(&server->mid_lock);
1018 /* now walk dispose list and issue callbacks */
1019 list_for_each_safe(tmp, tmp2, &dispose_list) {
1020 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
1021 cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
1022 list_del_init(&mid_entry->qhead);
1023 mid_entry->callback(mid_entry);
1024 release_mid(mid_entry);
1026 /* 1/8th of sec is more than enough time for them to exit */
1030 if (!list_empty(&server->pending_mid_q)) {
1032 * mpx threads have not exited yet give them at least the smb
1033 * send timeout time for long ops.
1035 * Due to delays on oplock break requests, we need to wait at
1036 * least 45 seconds before giving up on a request getting a
1037 * response and going ahead and killing cifsd.
1039 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
1042 * If threads still have not exited they are probably never
1043 * coming home not much else we can do but free the memory.
1047 #ifdef CONFIG_CIFS_DFS_UPCALL
1048 kfree(server->origin_fullpath);
1049 kfree(server->leaf_fullpath);
1053 length = atomic_dec_return(&tcpSesAllocCount);
1055 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1059 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1062 char *buf = server->smallbuf;
1063 unsigned int pdu_length = server->pdu_size;
1065 /* make sure this will fit in a large buffer */
1066 if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
1067 HEADER_PREAMBLE_SIZE(server)) {
1068 cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
1069 cifs_reconnect(server, true);
1070 return -ECONNABORTED;
1073 /* switch to large buffer if too big for a small one */
1074 if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
1075 server->large_buf = true;
1076 memcpy(server->bigbuf, buf, server->total_read);
1077 buf = server->bigbuf;
1080 /* now read the rest */
1081 length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
1082 pdu_length - MID_HEADER_SIZE(server));
1086 server->total_read += length;
1088 dump_smb(buf, server->total_read);
1090 return cifs_handle_standard(server, mid);
1094 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1096 char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1100 * We know that we received enough to get to the MID as we
1101 * checked the pdu_length earlier. Now check to see
1102 * if the rest of the header is OK.
1104 * 48 bytes is enough to display the header and a little bit
1105 * into the payload for debugging purposes.
1107 rc = server->ops->check_message(buf, server->total_read, server);
1109 cifs_dump_mem("Bad SMB: ", buf,
1110 min_t(unsigned int, server->total_read, 48));
1112 if (server->ops->is_session_expired &&
1113 server->ops->is_session_expired(buf)) {
1114 cifs_reconnect(server, true);
1118 if (server->ops->is_status_pending &&
1119 server->ops->is_status_pending(buf, server))
1125 handle_mid(mid, server, buf, rc);
1130 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1132 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1133 int scredits, in_flight;
1136 * SMB1 does not use credits.
1138 if (is_smb1(server))
1141 if (shdr->CreditRequest) {
1142 spin_lock(&server->req_lock);
1143 server->credits += le16_to_cpu(shdr->CreditRequest);
1144 scredits = server->credits;
1145 in_flight = server->in_flight;
1146 spin_unlock(&server->req_lock);
1147 wake_up(&server->request_q);
1149 trace_smb3_hdr_credits(server->CurrentMid,
1150 server->conn_id, server->hostname, scredits,
1151 le16_to_cpu(shdr->CreditRequest), in_flight);
1152 cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
1153 __func__, le16_to_cpu(shdr->CreditRequest),
1160 cifs_demultiplex_thread(void *p)
1162 int i, num_mids, length;
1163 struct TCP_Server_Info *server = p;
1164 unsigned int pdu_length;
1165 unsigned int next_offset;
1167 struct task_struct *task_to_wake = NULL;
1168 struct mid_q_entry *mids[MAX_COMPOUND];
1169 char *bufs[MAX_COMPOUND];
1170 unsigned int noreclaim_flag, num_io_timeout = 0;
1171 bool pending_reconnect = false;
1173 noreclaim_flag = memalloc_noreclaim_save();
1174 cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1176 length = atomic_inc_return(&tcpSesAllocCount);
1178 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1181 allow_kernel_signal(SIGKILL);
1182 while (server->tcpStatus != CifsExiting) {
1183 if (try_to_freeze())
1186 if (!allocate_buffers(server))
1189 server->large_buf = false;
1190 buf = server->smallbuf;
1191 pdu_length = 4; /* enough to get RFC1001 header */
1193 length = cifs_read_from_socket(server, buf, pdu_length);
1197 if (is_smb1(server))
1198 server->total_read = length;
1200 server->total_read = 0;
1203 * The right amount was read from socket - 4 bytes,
1204 * so we can now interpret the length field.
1206 pdu_length = get_rfc1002_length(buf);
1208 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1209 if (!is_smb_response(server, buf[0]))
1212 pending_reconnect = false;
1214 server->pdu_size = pdu_length;
1216 /* make sure we have enough to get to the MID */
1217 if (server->pdu_size < MID_HEADER_SIZE(server)) {
1218 cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1220 cifs_reconnect(server, true);
1224 /* read down to the MID */
1225 length = cifs_read_from_socket(server,
1226 buf + HEADER_PREAMBLE_SIZE(server),
1227 MID_HEADER_SIZE(server));
1230 server->total_read += length;
1232 if (server->ops->next_header) {
1233 if (server->ops->next_header(server, buf, &next_offset)) {
1234 cifs_dbg(VFS, "%s: malformed response (next_offset=%u)\n",
1235 __func__, next_offset);
1236 cifs_reconnect(server, true);
1240 server->pdu_size = next_offset;
1243 memset(mids, 0, sizeof(mids));
1244 memset(bufs, 0, sizeof(bufs));
1247 if (server->ops->is_transform_hdr &&
1248 server->ops->receive_transform &&
1249 server->ops->is_transform_hdr(buf)) {
1250 length = server->ops->receive_transform(server,
1255 mids[0] = server->ops->find_mid(server, buf);
1259 if (!mids[0] || !mids[0]->receive)
1260 length = standard_receive3(server, mids[0]);
1262 length = mids[0]->receive(server, mids[0]);
1266 for (i = 0; i < num_mids; i++)
1268 release_mid(mids[i]);
1272 if (server->ops->is_status_io_timeout &&
1273 server->ops->is_status_io_timeout(buf)) {
1275 if (num_io_timeout > MAX_STATUS_IO_TIMEOUT) {
1276 cifs_server_dbg(VFS,
1277 "Number of request timeouts exceeded %d. Reconnecting",
1278 MAX_STATUS_IO_TIMEOUT);
1280 pending_reconnect = true;
1285 server->lstrp = jiffies;
1287 for (i = 0; i < num_mids; i++) {
1288 if (mids[i] != NULL) {
1289 mids[i]->resp_buf_size = server->pdu_size;
1291 if (bufs[i] && server->ops->is_network_name_deleted)
1292 server->ops->is_network_name_deleted(bufs[i],
1295 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1296 mids[i]->callback(mids[i]);
1298 release_mid(mids[i]);
1299 } else if (server->ops->is_oplock_break &&
1300 server->ops->is_oplock_break(bufs[i],
1302 smb2_add_credits_from_hdr(bufs[i], server);
1303 cifs_dbg(FYI, "Received oplock break\n");
1305 cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1306 atomic_read(&mid_count));
1307 cifs_dump_mem("Received Data is: ", bufs[i],
1308 HEADER_SIZE(server));
1309 smb2_add_credits_from_hdr(bufs[i], server);
1310 #ifdef CONFIG_CIFS_DEBUG2
1311 if (server->ops->dump_detail)
1312 server->ops->dump_detail(bufs[i],
1314 cifs_dump_mids(server);
1315 #endif /* CIFS_DEBUG2 */
1319 if (pdu_length > server->pdu_size) {
1320 if (!allocate_buffers(server))
1322 pdu_length -= server->pdu_size;
1323 server->total_read = 0;
1324 server->large_buf = false;
1325 buf = server->smallbuf;
1329 /* do this reconnect at the very end after processing all MIDs */
1330 if (pending_reconnect)
1331 cifs_reconnect(server, true);
1333 } /* end while !EXITING */
1335 /* buffer usually freed in free_mid - need to free it here on exit */
1336 cifs_buf_release(server->bigbuf);
1337 if (server->smallbuf) /* no sense logging a debug message if NULL */
1338 cifs_small_buf_release(server->smallbuf);
1340 task_to_wake = xchg(&server->tsk, NULL);
1341 clean_demultiplex_info(server);
1343 /* if server->tsk was NULL then wait for a signal before exiting */
1344 if (!task_to_wake) {
1345 set_current_state(TASK_INTERRUPTIBLE);
1346 while (!signal_pending(current)) {
1348 set_current_state(TASK_INTERRUPTIBLE);
1350 set_current_state(TASK_RUNNING);
1353 memalloc_noreclaim_restore(noreclaim_flag);
1354 module_put_and_kthread_exit(0);
1358 cifs_ipaddr_cmp(struct sockaddr *srcaddr, struct sockaddr *rhs)
1360 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1361 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1362 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1363 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1365 switch (srcaddr->sa_family) {
1367 switch (rhs->sa_family) {
1377 switch (rhs->sa_family) {
1381 return memcmp(saddr4, vaddr4,
1382 sizeof(struct sockaddr_in));
1390 switch (rhs->sa_family) {
1395 return memcmp(saddr6,
1397 sizeof(struct sockaddr_in6));
1403 return -1; /* don't expect to be here */
1408 * Returns true if srcaddr isn't specified and rhs isn't specified, or
1409 * if srcaddr is specified and matches the IP address of the rhs argument
1412 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1414 switch (srcaddr->sa_family) {
1416 return (rhs->sa_family == AF_UNSPEC);
1418 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1419 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1420 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1423 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1424 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1425 return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
1429 return false; /* don't expect to be here */
1434 * If no port is specified in addr structure, we try to match with 445 port
1435 * and if it fails - with 139 ports. It should be called only if address
1436 * families of server and addr are equal.
1439 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1441 __be16 port, *sport;
1443 /* SMBDirect manages its own ports, don't match it here */
1447 switch (addr->sa_family) {
1449 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1450 port = ((struct sockaddr_in *) addr)->sin_port;
1453 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1454 port = ((struct sockaddr_in6 *) addr)->sin6_port;
1462 port = htons(CIFS_PORT);
1466 port = htons(RFC1001_PORT);
1469 return port == *sport;
1473 match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
1474 struct sockaddr *srcaddr)
1476 switch (addr->sa_family) {
1478 struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
1479 struct sockaddr_in *srv_addr4 =
1480 (struct sockaddr_in *)&server->dstaddr;
1482 if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
1487 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
1488 struct sockaddr_in6 *srv_addr6 =
1489 (struct sockaddr_in6 *)&server->dstaddr;
1491 if (!ipv6_addr_equal(&addr6->sin6_addr,
1492 &srv_addr6->sin6_addr))
1494 if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
1500 return false; /* don't expect to be here */
1503 if (!cifs_match_ipaddr(srcaddr, (struct sockaddr *)&server->srcaddr))
1510 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1513 * The select_sectype function should either return the ctx->sectype
1514 * that was specified, or "Unspecified" if that sectype was not
1515 * compatible with the given NEGOTIATE request.
1517 if (server->ops->select_sectype(server, ctx->sectype)
1522 * Now check if signing mode is acceptable. No need to check
1523 * global_secflags at this point since if MUST_SIGN is set then
1524 * the server->sign had better be too.
1526 if (ctx->sign && !server->sign)
1532 /* this function must be called with srv_lock held */
1533 static int match_server(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1535 struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1537 lockdep_assert_held(&server->srv_lock);
1539 if (ctx->nosharesock)
1542 /* this server does not share socket */
1543 if (server->nosharesock)
1546 /* If multidialect negotiation see if existing sessions match one */
1547 if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1548 if (server->vals->protocol_id < SMB30_PROT_ID)
1550 } else if (strcmp(ctx->vals->version_string,
1551 SMBDEFAULT_VERSION_STRING) == 0) {
1552 if (server->vals->protocol_id < SMB21_PROT_ID)
1554 } else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1557 if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1560 if (strcasecmp(server->hostname, ctx->server_hostname))
1563 if (!match_address(server, addr,
1564 (struct sockaddr *)&ctx->srcaddr))
1567 if (!match_port(server, addr))
1570 if (!match_security(server, ctx))
1573 if (server->echo_interval != ctx->echo_interval * HZ)
1576 if (server->rdma != ctx->rdma)
1579 if (server->ignore_signature != ctx->ignore_signature)
1582 if (server->min_offload != ctx->min_offload)
1588 struct TCP_Server_Info *
1589 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1591 struct TCP_Server_Info *server;
1593 spin_lock(&cifs_tcp_ses_lock);
1594 list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1595 spin_lock(&server->srv_lock);
1596 #ifdef CONFIG_CIFS_DFS_UPCALL
1598 * DFS failover implementation in cifs_reconnect() requires unique tcp sessions for
1599 * DFS connections to do failover properly, so avoid sharing them with regular
1600 * shares or even links that may connect to same server but having completely
1601 * different failover targets.
1603 if (server->is_dfs_conn) {
1604 spin_unlock(&server->srv_lock);
1609 * Skip ses channels since they're only handled in lower layers
1610 * (e.g. cifs_send_recv).
1612 if (CIFS_SERVER_IS_CHAN(server) || !match_server(server, ctx)) {
1613 spin_unlock(&server->srv_lock);
1616 spin_unlock(&server->srv_lock);
1618 ++server->srv_count;
1619 spin_unlock(&cifs_tcp_ses_lock);
1620 cifs_dbg(FYI, "Existing tcp session with server found\n");
1623 spin_unlock(&cifs_tcp_ses_lock);
1628 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1630 struct task_struct *task;
1632 spin_lock(&cifs_tcp_ses_lock);
1633 if (--server->srv_count > 0) {
1634 spin_unlock(&cifs_tcp_ses_lock);
1638 /* srv_count can never go negative */
1639 WARN_ON(server->srv_count < 0);
1641 put_net(cifs_net_ns(server));
1643 list_del_init(&server->tcp_ses_list);
1644 spin_unlock(&cifs_tcp_ses_lock);
1646 /* For secondary channels, we pick up ref-count on the primary server */
1647 if (CIFS_SERVER_IS_CHAN(server))
1648 cifs_put_tcp_session(server->primary_server, from_reconnect);
1650 cancel_delayed_work_sync(&server->echo);
1651 cancel_delayed_work_sync(&server->resolve);
1655 * Avoid deadlock here: reconnect work calls
1656 * cifs_put_tcp_session() at its end. Need to be sure
1657 * that reconnect work does nothing with server pointer after
1660 cancel_delayed_work(&server->reconnect);
1662 cancel_delayed_work_sync(&server->reconnect);
1664 spin_lock(&server->srv_lock);
1665 server->tcpStatus = CifsExiting;
1666 spin_unlock(&server->srv_lock);
1668 cifs_crypto_secmech_release(server);
1670 kfree_sensitive(server->session_key.response);
1671 server->session_key.response = NULL;
1672 server->session_key.len = 0;
1673 kfree(server->hostname);
1674 server->hostname = NULL;
1676 task = xchg(&server->tsk, NULL);
1678 send_sig(SIGKILL, task, 1);
1681 struct TCP_Server_Info *
1682 cifs_get_tcp_session(struct smb3_fs_context *ctx,
1683 struct TCP_Server_Info *primary_server)
1685 struct TCP_Server_Info *tcp_ses = NULL;
1688 cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1690 /* see if we already have a matching tcp_ses */
1691 tcp_ses = cifs_find_tcp_session(ctx);
1695 tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1701 tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1702 if (!tcp_ses->hostname) {
1707 if (ctx->nosharesock)
1708 tcp_ses->nosharesock = true;
1710 tcp_ses->ops = ctx->ops;
1711 tcp_ses->vals = ctx->vals;
1712 cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1714 tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1715 tcp_ses->noblockcnt = ctx->rootfs;
1716 tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1717 tcp_ses->noautotune = ctx->noautotune;
1718 tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1719 tcp_ses->rdma = ctx->rdma;
1720 tcp_ses->in_flight = 0;
1721 tcp_ses->max_in_flight = 0;
1722 tcp_ses->credits = 1;
1723 if (primary_server) {
1724 spin_lock(&cifs_tcp_ses_lock);
1725 ++primary_server->srv_count;
1726 spin_unlock(&cifs_tcp_ses_lock);
1727 tcp_ses->primary_server = primary_server;
1729 init_waitqueue_head(&tcp_ses->response_q);
1730 init_waitqueue_head(&tcp_ses->request_q);
1731 INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1732 mutex_init(&tcp_ses->_srv_mutex);
1733 memcpy(tcp_ses->workstation_RFC1001_name,
1734 ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1735 memcpy(tcp_ses->server_RFC1001_name,
1736 ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1737 tcp_ses->session_estab = false;
1738 tcp_ses->sequence_number = 0;
1739 tcp_ses->channel_sequence_num = 0; /* only tracked for primary channel */
1740 tcp_ses->reconnect_instance = 1;
1741 tcp_ses->lstrp = jiffies;
1742 tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1743 spin_lock_init(&tcp_ses->req_lock);
1744 spin_lock_init(&tcp_ses->srv_lock);
1745 spin_lock_init(&tcp_ses->mid_lock);
1746 INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1747 INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1748 INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1749 INIT_DELAYED_WORK(&tcp_ses->resolve, cifs_resolve_server);
1750 INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1751 mutex_init(&tcp_ses->reconnect_mutex);
1752 #ifdef CONFIG_CIFS_DFS_UPCALL
1753 mutex_init(&tcp_ses->refpath_lock);
1755 memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1756 sizeof(tcp_ses->srcaddr));
1757 memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1758 sizeof(tcp_ses->dstaddr));
1759 if (ctx->use_client_guid)
1760 memcpy(tcp_ses->client_guid, ctx->client_guid,
1761 SMB2_CLIENT_GUID_SIZE);
1763 generate_random_uuid(tcp_ses->client_guid);
1765 * at this point we are the only ones with the pointer
1766 * to the struct since the kernel thread not created yet
1767 * no need to spinlock this init of tcpStatus or srv_count
1769 tcp_ses->tcpStatus = CifsNew;
1770 ++tcp_ses->srv_count;
1772 if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1773 ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1774 tcp_ses->echo_interval = ctx->echo_interval * HZ;
1776 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1777 if (tcp_ses->rdma) {
1778 #ifndef CONFIG_CIFS_SMB_DIRECT
1779 cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1781 goto out_err_crypto_release;
1783 tcp_ses->smbd_conn = smbd_get_connection(
1784 tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1785 if (tcp_ses->smbd_conn) {
1786 cifs_dbg(VFS, "RDMA transport established\n");
1788 goto smbd_connected;
1791 goto out_err_crypto_release;
1794 rc = ip_connect(tcp_ses);
1796 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1797 goto out_err_crypto_release;
1801 * since we're in a cifs function already, we know that
1802 * this will succeed. No need for try_module_get().
1804 __module_get(THIS_MODULE);
1805 tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1807 if (IS_ERR(tcp_ses->tsk)) {
1808 rc = PTR_ERR(tcp_ses->tsk);
1809 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1810 module_put(THIS_MODULE);
1811 goto out_err_crypto_release;
1813 tcp_ses->min_offload = ctx->min_offload;
1815 * at this point we are the only ones with the pointer
1816 * to the struct since the kernel thread not created yet
1817 * no need to spinlock this update of tcpStatus
1819 spin_lock(&tcp_ses->srv_lock);
1820 tcp_ses->tcpStatus = CifsNeedNegotiate;
1821 spin_unlock(&tcp_ses->srv_lock);
1823 if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1824 tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1826 tcp_ses->max_credits = ctx->max_credits;
1828 tcp_ses->nr_targets = 1;
1829 tcp_ses->ignore_signature = ctx->ignore_signature;
1830 /* thread spawned, put it on the list */
1831 spin_lock(&cifs_tcp_ses_lock);
1832 list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1833 spin_unlock(&cifs_tcp_ses_lock);
1835 /* queue echo request delayed work */
1836 queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1838 /* queue dns resolution delayed work */
1839 cifs_dbg(FYI, "%s: next dns resolution scheduled for %d seconds in the future\n",
1840 __func__, SMB_DNS_RESOLVE_INTERVAL_DEFAULT);
1842 queue_delayed_work(cifsiod_wq, &tcp_ses->resolve, (SMB_DNS_RESOLVE_INTERVAL_DEFAULT * HZ));
1846 out_err_crypto_release:
1847 cifs_crypto_secmech_release(tcp_ses);
1849 put_net(cifs_net_ns(tcp_ses));
1853 if (CIFS_SERVER_IS_CHAN(tcp_ses))
1854 cifs_put_tcp_session(tcp_ses->primary_server, false);
1855 kfree(tcp_ses->hostname);
1856 if (tcp_ses->ssocket)
1857 sock_release(tcp_ses->ssocket);
1863 /* this function must be called with ses_lock and chan_lock held */
1864 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1866 if (ctx->sectype != Unspecified &&
1867 ctx->sectype != ses->sectype)
1871 * If an existing session is limited to less channels than
1872 * requested, it should not be reused
1874 if (ses->chan_max < ctx->max_channels)
1877 switch (ses->sectype) {
1879 if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1883 /* NULL username means anonymous session */
1884 if (ses->user_name == NULL) {
1890 /* anything else takes username/password */
1891 if (strncmp(ses->user_name,
1892 ctx->username ? ctx->username : "",
1893 CIFS_MAX_USERNAME_LEN))
1895 if ((ctx->username && strlen(ctx->username) != 0) &&
1896 ses->password != NULL &&
1897 strncmp(ses->password,
1898 ctx->password ? ctx->password : "",
1899 CIFS_MAX_PASSWORD_LEN))
1906 * cifs_setup_ipc - helper to setup the IPC tcon for the session
1907 * @ses: smb session to issue the request on
1908 * @ctx: the superblock configuration context to use for building the
1909 * new tree connection for the IPC (interprocess communication RPC)
1911 * A new IPC connection is made and stored in the session
1912 * tcon_ipc. The IPC tcon has the same lifetime as the session.
1915 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1918 struct cifs_tcon *tcon;
1919 char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1921 struct TCP_Server_Info *server = ses->server;
1924 * If the mount request that resulted in the creation of the
1925 * session requires encryption, force IPC to be encrypted too.
1928 if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1931 cifs_server_dbg(VFS,
1932 "IPC: server doesn't support encryption\n");
1937 tcon = tconInfoAlloc();
1941 spin_lock(&server->srv_lock);
1942 scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1943 spin_unlock(&server->srv_lock);
1949 rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1953 cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1958 cifs_dbg(FYI, "IPC tcon rc=%d ipc tid=0x%x\n", rc, tcon->tid);
1960 spin_lock(&tcon->tc_lock);
1961 tcon->status = TID_GOOD;
1962 spin_unlock(&tcon->tc_lock);
1963 ses->tcon_ipc = tcon;
1969 * cifs_free_ipc - helper to release the session IPC tcon
1970 * @ses: smb session to unmount the IPC from
1972 * Needs to be called everytime a session is destroyed.
1974 * On session close, the IPC is closed and the server must release all tcons of the session.
1975 * No need to send a tree disconnect here.
1977 * Besides, it will make the server to not close durable and resilient files on session close, as
1978 * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1981 cifs_free_ipc(struct cifs_ses *ses)
1983 struct cifs_tcon *tcon = ses->tcon_ipc;
1989 ses->tcon_ipc = NULL;
1993 static struct cifs_ses *
1994 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1996 struct cifs_ses *ses;
1998 spin_lock(&cifs_tcp_ses_lock);
1999 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2000 spin_lock(&ses->ses_lock);
2001 if (ses->ses_status == SES_EXITING) {
2002 spin_unlock(&ses->ses_lock);
2005 spin_lock(&ses->chan_lock);
2006 if (!match_session(ses, ctx)) {
2007 spin_unlock(&ses->chan_lock);
2008 spin_unlock(&ses->ses_lock);
2011 spin_unlock(&ses->chan_lock);
2012 spin_unlock(&ses->ses_lock);
2015 spin_unlock(&cifs_tcp_ses_lock);
2018 spin_unlock(&cifs_tcp_ses_lock);
2022 void cifs_put_smb_ses(struct cifs_ses *ses)
2024 unsigned int rc, xid;
2025 unsigned int chan_count;
2026 struct TCP_Server_Info *server = ses->server;
2028 spin_lock(&ses->ses_lock);
2029 if (ses->ses_status == SES_EXITING) {
2030 spin_unlock(&ses->ses_lock);
2033 spin_unlock(&ses->ses_lock);
2035 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
2037 "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->tree_name : "NONE");
2039 spin_lock(&cifs_tcp_ses_lock);
2040 if (--ses->ses_count > 0) {
2041 spin_unlock(&cifs_tcp_ses_lock);
2044 spin_unlock(&cifs_tcp_ses_lock);
2046 /* ses_count can never go negative */
2047 WARN_ON(ses->ses_count < 0);
2049 if (ses->ses_status == SES_GOOD)
2050 ses->ses_status = SES_EXITING;
2054 if (ses->ses_status == SES_EXITING && server->ops->logoff) {
2056 rc = server->ops->logoff(xid, ses);
2058 cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
2063 spin_lock(&cifs_tcp_ses_lock);
2064 list_del_init(&ses->smb_ses_list);
2065 spin_unlock(&cifs_tcp_ses_lock);
2067 chan_count = ses->chan_count;
2069 /* close any extra channels */
2070 if (chan_count > 1) {
2073 for (i = 1; i < chan_count; i++) {
2074 if (ses->chans[i].iface) {
2075 kref_put(&ses->chans[i].iface->refcount, release_iface);
2076 ses->chans[i].iface = NULL;
2078 cifs_put_tcp_session(ses->chans[i].server, 0);
2079 ses->chans[i].server = NULL;
2083 /* we now account for primary channel in iface->refcount */
2084 if (ses->chans[0].iface) {
2085 kref_put(&ses->chans[0].iface->refcount, release_iface);
2086 ses->chans[0].server = NULL;
2090 cifs_put_tcp_session(server, 0);
2095 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2096 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2098 /* Populate username and pw fields from keyring if possible */
2100 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
2104 const char *delim, *payload;
2108 struct TCP_Server_Info *server = ses->server;
2109 struct sockaddr_in *sa;
2110 struct sockaddr_in6 *sa6;
2111 const struct user_key_payload *upayload;
2113 desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2117 /* try to find an address key first */
2118 switch (server->dstaddr.ss_family) {
2120 sa = (struct sockaddr_in *)&server->dstaddr;
2121 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2124 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2125 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2128 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2129 server->dstaddr.ss_family);
2134 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2135 key = request_key(&key_type_logon, desc, "");
2137 if (!ses->domainName) {
2138 cifs_dbg(FYI, "domainName is NULL\n");
2143 /* didn't work, try to find a domain key */
2144 sprintf(desc, "cifs:d:%s", ses->domainName);
2145 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2146 key = request_key(&key_type_logon, desc, "");
2154 down_read(&key->sem);
2155 upayload = user_key_payload_locked(key);
2156 if (IS_ERR_OR_NULL(upayload)) {
2157 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2161 /* find first : in payload */
2162 payload = upayload->data;
2163 delim = strnchr(payload, upayload->datalen, ':');
2164 cifs_dbg(FYI, "payload=%s\n", payload);
2166 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2172 len = delim - payload;
2173 if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2174 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2180 ctx->username = kstrndup(payload, len, GFP_KERNEL);
2181 if (!ctx->username) {
2182 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2187 cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
2189 len = key->datalen - (len + 1);
2190 if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2191 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2193 kfree(ctx->username);
2194 ctx->username = NULL;
2199 ctx->password = kstrndup(delim, len, GFP_KERNEL);
2200 if (!ctx->password) {
2201 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2204 kfree(ctx->username);
2205 ctx->username = NULL;
2210 * If we have a domain key then we must set the domainName in the
2213 if (is_domain && ses->domainName) {
2214 ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2215 if (!ctx->domainname) {
2216 cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
2219 kfree(ctx->username);
2220 ctx->username = NULL;
2221 kfree_sensitive(ctx->password);
2222 ctx->password = NULL;
2227 strscpy(ctx->workstation_name, ses->workstation_name, sizeof(ctx->workstation_name));
2234 cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2237 #else /* ! CONFIG_KEYS */
2239 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2240 struct cifs_ses *ses __attribute__((unused)))
2244 #endif /* CONFIG_KEYS */
2247 * cifs_get_smb_ses - get a session matching @ctx data from @server
2248 * @server: server to setup the session to
2249 * @ctx: superblock configuration context to use to setup the session
2251 * This function assumes it is being called from cifs_mount() where we
2252 * already got a server reference (server refcount +1). See
2253 * cifs_get_tcon() for refcount explanations.
2256 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2260 struct cifs_ses *ses;
2261 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2262 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2266 ses = cifs_find_smb_ses(server, ctx);
2268 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2271 spin_lock(&ses->chan_lock);
2272 if (cifs_chan_needs_reconnect(ses, server)) {
2273 spin_unlock(&ses->chan_lock);
2274 cifs_dbg(FYI, "Session needs reconnect\n");
2276 mutex_lock(&ses->session_mutex);
2277 rc = cifs_negotiate_protocol(xid, ses, server);
2279 mutex_unlock(&ses->session_mutex);
2280 /* problem -- put our ses reference */
2281 cifs_put_smb_ses(ses);
2286 rc = cifs_setup_session(xid, ses, server,
2289 mutex_unlock(&ses->session_mutex);
2290 /* problem -- put our reference */
2291 cifs_put_smb_ses(ses);
2295 mutex_unlock(&ses->session_mutex);
2297 spin_lock(&ses->chan_lock);
2299 spin_unlock(&ses->chan_lock);
2301 /* existing SMB ses has a server reference already */
2302 cifs_put_tcp_session(server, 0);
2309 cifs_dbg(FYI, "Existing smb sess not found\n");
2310 ses = sesInfoAlloc();
2314 /* new SMB session uses our server ref */
2315 ses->server = server;
2316 if (server->dstaddr.ss_family == AF_INET6)
2317 sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2319 sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2321 if (ctx->username) {
2322 ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2323 if (!ses->user_name)
2327 /* ctx->password freed at unmount */
2328 if (ctx->password) {
2329 ses->password = kstrdup(ctx->password, GFP_KERNEL);
2333 if (ctx->domainname) {
2334 ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2335 if (!ses->domainName)
2339 strscpy(ses->workstation_name, ctx->workstation_name, sizeof(ses->workstation_name));
2341 if (ctx->domainauto)
2342 ses->domainAuto = ctx->domainauto;
2343 ses->cred_uid = ctx->cred_uid;
2344 ses->linux_uid = ctx->linux_uid;
2346 ses->sectype = ctx->sectype;
2347 ses->sign = ctx->sign;
2349 /* add server as first channel */
2350 spin_lock(&ses->chan_lock);
2351 ses->chans[0].server = server;
2352 ses->chan_count = 1;
2353 ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2354 ses->chans_need_reconnect = 1;
2355 spin_unlock(&ses->chan_lock);
2357 mutex_lock(&ses->session_mutex);
2358 rc = cifs_negotiate_protocol(xid, ses, server);
2360 rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2361 mutex_unlock(&ses->session_mutex);
2363 /* each channel uses a different signing key */
2364 spin_lock(&ses->chan_lock);
2365 memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2366 sizeof(ses->smb3signingkey));
2367 spin_unlock(&ses->chan_lock);
2373 * success, put it on the list and add it as first channel
2374 * note: the session becomes active soon after this. So you'll
2375 * need to lock before changing something in the session.
2377 spin_lock(&cifs_tcp_ses_lock);
2378 list_add(&ses->smb_ses_list, &server->smb_ses_list);
2379 spin_unlock(&cifs_tcp_ses_lock);
2381 cifs_setup_ipc(ses, ctx);
2393 /* this function must be called with tc_lock held */
2394 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2396 if (tcon->status == TID_EXITING)
2398 if (strncmp(tcon->tree_name, ctx->UNC, MAX_TREE_SIZE))
2400 if (tcon->seal != ctx->seal)
2402 if (tcon->snapshot_time != ctx->snapshot_time)
2404 if (tcon->handle_timeout != ctx->handle_timeout)
2406 if (tcon->no_lease != ctx->no_lease)
2408 if (tcon->nodelete != ctx->nodelete)
2413 static struct cifs_tcon *
2414 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2416 struct cifs_tcon *tcon;
2418 spin_lock(&cifs_tcp_ses_lock);
2419 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2420 spin_lock(&tcon->tc_lock);
2421 if (!match_tcon(tcon, ctx)) {
2422 spin_unlock(&tcon->tc_lock);
2426 spin_unlock(&tcon->tc_lock);
2427 spin_unlock(&cifs_tcp_ses_lock);
2430 spin_unlock(&cifs_tcp_ses_lock);
2435 cifs_put_tcon(struct cifs_tcon *tcon)
2438 struct cifs_ses *ses;
2441 * IPC tcon share the lifetime of their session and are
2442 * destroyed in the session put function
2444 if (tcon == NULL || tcon->ipc)
2448 cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2449 spin_lock(&cifs_tcp_ses_lock);
2450 spin_lock(&tcon->tc_lock);
2451 if (--tcon->tc_count > 0) {
2452 spin_unlock(&tcon->tc_lock);
2453 spin_unlock(&cifs_tcp_ses_lock);
2457 /* tc_count can never go negative */
2458 WARN_ON(tcon->tc_count < 0);
2460 list_del_init(&tcon->tcon_list);
2461 tcon->status = TID_EXITING;
2462 spin_unlock(&tcon->tc_lock);
2463 spin_unlock(&cifs_tcp_ses_lock);
2465 /* cancel polling of interfaces */
2466 cancel_delayed_work_sync(&tcon->query_interfaces);
2468 if (tcon->use_witness) {
2471 rc = cifs_swn_unregister(tcon);
2473 cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2479 if (ses->server->ops->tree_disconnect)
2480 ses->server->ops->tree_disconnect(xid, tcon);
2483 cifs_fscache_release_super_cookie(tcon);
2485 cifs_put_smb_ses(ses);
2489 * cifs_get_tcon - get a tcon matching @ctx data from @ses
2490 * @ses: smb session to issue the request on
2491 * @ctx: the superblock configuration context to use for building the
2493 * - tcon refcount is the number of mount points using the tcon.
2494 * - ses refcount is the number of tcon using the session.
2496 * 1. This function assumes it is being called from cifs_mount() where
2497 * we already got a session reference (ses refcount +1).
2499 * 2. Since we're in the context of adding a mount point, the end
2500 * result should be either:
2502 * a) a new tcon already allocated with refcount=1 (1 mount point) and
2503 * its session refcount incremented (1 new tcon). This +1 was
2504 * already done in (1).
2506 * b) an existing tcon with refcount+1 (add a mount point to it) and
2507 * identical ses refcount (no new tcon). Because of (1) we need to
2508 * decrement the ses refcount.
2510 static struct cifs_tcon *
2511 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2514 struct cifs_tcon *tcon;
2516 tcon = cifs_find_tcon(ses, ctx);
2519 * tcon has refcount already incremented but we need to
2520 * decrement extra ses reference gotten by caller (case b)
2522 cifs_dbg(FYI, "Found match on UNC path\n");
2523 cifs_put_smb_ses(ses);
2527 if (!ses->server->ops->tree_connect) {
2532 tcon = tconInfoAlloc();
2538 if (ctx->snapshot_time) {
2539 if (ses->server->vals->protocol_id == 0) {
2541 "Use SMB2 or later for snapshot mount option\n");
2545 tcon->snapshot_time = ctx->snapshot_time;
2548 if (ctx->handle_timeout) {
2549 if (ses->server->vals->protocol_id == 0) {
2551 "Use SMB2.1 or later for handle timeout option\n");
2555 tcon->handle_timeout = ctx->handle_timeout;
2559 if (ctx->password) {
2560 tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2561 if (!tcon->password) {
2568 if (ses->server->vals->protocol_id == 0) {
2570 "SMB3 or later required for encryption\n");
2573 } else if (tcon->ses->server->capabilities &
2574 SMB2_GLOBAL_CAP_ENCRYPTION)
2577 cifs_dbg(VFS, "Encryption is not supported on share\n");
2583 if (ctx->linux_ext) {
2584 if (ses->server->posix_ext_supported) {
2585 tcon->posix_extensions = true;
2586 pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2587 } else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
2588 (strcmp(ses->server->vals->version_string,
2589 SMB3ANY_VERSION_STRING) == 0) ||
2590 (strcmp(ses->server->vals->version_string,
2591 SMBDEFAULT_VERSION_STRING) == 0)) {
2592 cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2596 cifs_dbg(VFS, "Check vers= mount option. SMB3.11 "
2597 "disabled but required for POSIX extensions\n");
2604 rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2607 cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2611 tcon->use_persistent = false;
2612 /* check if SMB2 or later, CIFS does not support persistent handles */
2613 if (ctx->persistent) {
2614 if (ses->server->vals->protocol_id == 0) {
2616 "SMB3 or later required for persistent handles\n");
2619 } else if (ses->server->capabilities &
2620 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2621 tcon->use_persistent = true;
2622 else /* persistent handles requested but not supported */ {
2624 "Persistent handles not supported on share\n");
2628 } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2629 && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2630 && (ctx->nopersistent == false)) {
2631 cifs_dbg(FYI, "enabling persistent handles\n");
2632 tcon->use_persistent = true;
2633 } else if (ctx->resilient) {
2634 if (ses->server->vals->protocol_id == 0) {
2636 "SMB2.1 or later required for resilient handles\n");
2640 tcon->use_resilient = true;
2643 tcon->use_witness = false;
2644 if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2645 if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2646 if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2648 * Set witness in use flag in first place
2649 * to retry registration in the echo task
2651 tcon->use_witness = true;
2652 /* And try to register immediately */
2653 rc = cifs_swn_register(tcon);
2655 cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2659 /* TODO: try to extend for non-cluster uses (eg multichannel) */
2660 cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2665 cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2671 /* If the user really knows what they are doing they can override */
2672 if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2674 cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2675 else if (ctx->cache_rw)
2676 cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2679 if (ctx->no_lease) {
2680 if (ses->server->vals->protocol_id == 0) {
2682 "SMB2 or later required for nolease option\n");
2686 tcon->no_lease = ctx->no_lease;
2690 * We can have only one retry value for a connection to a share so for
2691 * resources mounted more than once to the same server share the last
2692 * value passed in for the retry flag is used.
2694 tcon->retry = ctx->retry;
2695 tcon->nocase = ctx->nocase;
2696 tcon->broken_sparse_sup = ctx->no_sparse;
2697 if (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING)
2698 tcon->nohandlecache = ctx->nohandlecache;
2700 tcon->nohandlecache = true;
2701 tcon->nodelete = ctx->nodelete;
2702 tcon->local_lease = ctx->local_lease;
2703 INIT_LIST_HEAD(&tcon->pending_opens);
2704 tcon->status = TID_GOOD;
2706 INIT_DELAYED_WORK(&tcon->query_interfaces,
2707 smb2_query_server_interfaces);
2708 if (ses->server->dialect >= SMB30_PROT_ID &&
2709 (ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
2710 /* schedule query interfaces poll */
2711 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
2712 (SMB_INTERFACE_POLL_INTERVAL * HZ));
2715 spin_lock(&cifs_tcp_ses_lock);
2716 list_add(&tcon->tcon_list, &ses->tcon_list);
2717 spin_unlock(&cifs_tcp_ses_lock);
2727 cifs_put_tlink(struct tcon_link *tlink)
2729 if (!tlink || IS_ERR(tlink))
2732 if (!atomic_dec_and_test(&tlink->tl_count) ||
2733 test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2734 tlink->tl_time = jiffies;
2738 if (!IS_ERR(tlink_tcon(tlink)))
2739 cifs_put_tcon(tlink_tcon(tlink));
2745 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2747 struct cifs_sb_info *old = CIFS_SB(sb);
2748 struct cifs_sb_info *new = mnt_data->cifs_sb;
2749 unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2750 unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2752 if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2755 if (old->mnt_cifs_serverino_autodisabled)
2756 newflags &= ~CIFS_MOUNT_SERVER_INUM;
2758 if (oldflags != newflags)
2762 * We want to share sb only if we don't specify an r/wsize or
2763 * specified r/wsize is greater than or equal to existing one.
2765 if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2768 if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2771 if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2772 !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2775 if (old->ctx->file_mode != new->ctx->file_mode ||
2776 old->ctx->dir_mode != new->ctx->dir_mode)
2779 if (strcmp(old->local_nls->charset, new->local_nls->charset))
2782 if (old->ctx->acregmax != new->ctx->acregmax)
2784 if (old->ctx->acdirmax != new->ctx->acdirmax)
2786 if (old->ctx->closetimeo != new->ctx->closetimeo)
2793 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2795 struct cifs_sb_info *old = CIFS_SB(sb);
2796 struct cifs_sb_info *new = mnt_data->cifs_sb;
2797 bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2799 bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2802 if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2804 else if (!old_set && !new_set)
2811 cifs_match_super(struct super_block *sb, void *data)
2813 struct cifs_mnt_data *mnt_data = data;
2814 struct smb3_fs_context *ctx;
2815 struct cifs_sb_info *cifs_sb;
2816 struct TCP_Server_Info *tcp_srv;
2817 struct cifs_ses *ses;
2818 struct cifs_tcon *tcon;
2819 struct tcon_link *tlink;
2822 spin_lock(&cifs_tcp_ses_lock);
2823 cifs_sb = CIFS_SB(sb);
2825 /* We do not want to use a superblock that has been shutdown */
2826 if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
2827 spin_unlock(&cifs_tcp_ses_lock);
2831 tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2832 if (tlink == NULL) {
2833 /* can not match superblock if tlink were ever null */
2834 spin_unlock(&cifs_tcp_ses_lock);
2837 tcon = tlink_tcon(tlink);
2839 tcp_srv = ses->server;
2841 ctx = mnt_data->ctx;
2843 spin_lock(&tcp_srv->srv_lock);
2844 spin_lock(&ses->ses_lock);
2845 spin_lock(&ses->chan_lock);
2846 spin_lock(&tcon->tc_lock);
2847 if (!match_server(tcp_srv, ctx) ||
2848 !match_session(ses, ctx) ||
2849 !match_tcon(tcon, ctx) ||
2850 !match_prepath(sb, mnt_data)) {
2855 rc = compare_mount_options(sb, mnt_data);
2857 spin_unlock(&tcon->tc_lock);
2858 spin_unlock(&ses->chan_lock);
2859 spin_unlock(&ses->ses_lock);
2860 spin_unlock(&tcp_srv->srv_lock);
2862 spin_unlock(&cifs_tcp_ses_lock);
2863 cifs_put_tlink(tlink);
2867 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2868 static struct lock_class_key cifs_key[2];
2869 static struct lock_class_key cifs_slock_key[2];
2872 cifs_reclassify_socket4(struct socket *sock)
2874 struct sock *sk = sock->sk;
2875 BUG_ON(!sock_allow_reclassification(sk));
2876 sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2877 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2881 cifs_reclassify_socket6(struct socket *sock)
2883 struct sock *sk = sock->sk;
2884 BUG_ON(!sock_allow_reclassification(sk));
2885 sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2886 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2890 cifs_reclassify_socket4(struct socket *sock)
2895 cifs_reclassify_socket6(struct socket *sock)
2900 /* See RFC1001 section 14 on representation of Netbios names */
2901 static void rfc1002mangle(char *target, char *source, unsigned int length)
2905 for (i = 0, j = 0; i < (length); i++) {
2906 /* mask a nibble at a time and encode */
2907 target[j] = 'A' + (0x0F & (source[i] >> 4));
2908 target[j+1] = 'A' + (0x0F & source[i]);
2915 bind_socket(struct TCP_Server_Info *server)
2918 if (server->srcaddr.ss_family != AF_UNSPEC) {
2919 /* Bind to the specified local IP address */
2920 struct socket *socket = server->ssocket;
2921 rc = kernel_bind(socket,
2922 (struct sockaddr *) &server->srcaddr,
2923 sizeof(server->srcaddr));
2925 struct sockaddr_in *saddr4;
2926 struct sockaddr_in6 *saddr6;
2927 saddr4 = (struct sockaddr_in *)&server->srcaddr;
2928 saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2929 if (saddr6->sin6_family == AF_INET6)
2930 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2931 &saddr6->sin6_addr, rc);
2933 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2934 &saddr4->sin_addr.s_addr, rc);
2941 ip_rfc1001_connect(struct TCP_Server_Info *server)
2945 * some servers require RFC1001 sessinit before sending
2946 * negprot - BB check reconnection in case where second
2947 * sessinit is sent but no second negprot
2949 struct rfc1002_session_packet req = {};
2950 struct smb_hdr *smb_buf = (struct smb_hdr *)&req;
2953 req.trailer.session_req.called_len = sizeof(req.trailer.session_req.called_name);
2955 if (server->server_RFC1001_name[0] != 0)
2956 rfc1002mangle(req.trailer.session_req.called_name,
2957 server->server_RFC1001_name,
2958 RFC1001_NAME_LEN_WITH_NULL);
2960 rfc1002mangle(req.trailer.session_req.called_name,
2961 DEFAULT_CIFS_CALLED_NAME,
2962 RFC1001_NAME_LEN_WITH_NULL);
2964 req.trailer.session_req.calling_len = sizeof(req.trailer.session_req.calling_name);
2966 /* calling name ends in null (byte 16) from old smb convention */
2967 if (server->workstation_RFC1001_name[0] != 0)
2968 rfc1002mangle(req.trailer.session_req.calling_name,
2969 server->workstation_RFC1001_name,
2970 RFC1001_NAME_LEN_WITH_NULL);
2972 rfc1002mangle(req.trailer.session_req.calling_name,
2974 RFC1001_NAME_LEN_WITH_NULL);
2977 * As per rfc1002, @len must be the number of bytes that follows the
2978 * length field of a rfc1002 session request payload.
2980 len = sizeof(req) - offsetof(struct rfc1002_session_packet, trailer.session_req);
2982 smb_buf->smb_buf_length = cpu_to_be32((RFC1002_SESSION_REQUEST << 24) | len);
2983 rc = smb_send(server, smb_buf, len);
2985 * RFC1001 layer in at least one server requires very short break before
2986 * negprot presumably because not expecting negprot to follow so fast.
2987 * This is a simple solution that works without complicating the code
2988 * and causes no significant slowing down on mount for everyone else
2990 usleep_range(1000, 2000);
2996 generic_ip_connect(struct TCP_Server_Info *server)
3001 struct socket *socket = server->ssocket;
3002 struct sockaddr *saddr;
3004 saddr = (struct sockaddr *) &server->dstaddr;
3006 if (server->dstaddr.ss_family == AF_INET6) {
3007 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
3009 sport = ipv6->sin6_port;
3010 slen = sizeof(struct sockaddr_in6);
3012 cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
3015 struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
3017 sport = ipv4->sin_port;
3018 slen = sizeof(struct sockaddr_in);
3020 cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
3024 if (socket == NULL) {
3025 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
3026 IPPROTO_TCP, &socket, 1);
3028 cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
3029 server->ssocket = NULL;
3033 /* BB other socket options to set KEEPALIVE, NODELAY? */
3034 cifs_dbg(FYI, "Socket created\n");
3035 server->ssocket = socket;
3036 socket->sk->sk_allocation = GFP_NOFS;
3037 if (sfamily == AF_INET6)
3038 cifs_reclassify_socket6(socket);
3040 cifs_reclassify_socket4(socket);
3043 rc = bind_socket(server);
3048 * Eventually check for other socket options to change from
3049 * the default. sock_setsockopt not used because it expects
3052 socket->sk->sk_rcvtimeo = 7 * HZ;
3053 socket->sk->sk_sndtimeo = 5 * HZ;
3055 /* make the bufsizes depend on wsize/rsize and max requests */
3056 if (server->noautotune) {
3057 if (socket->sk->sk_sndbuf < (200 * 1024))
3058 socket->sk->sk_sndbuf = 200 * 1024;
3059 if (socket->sk->sk_rcvbuf < (140 * 1024))
3060 socket->sk->sk_rcvbuf = 140 * 1024;
3063 if (server->tcp_nodelay)
3064 tcp_sock_set_nodelay(socket->sk);
3066 cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3067 socket->sk->sk_sndbuf,
3068 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3070 rc = kernel_connect(socket, saddr, slen,
3071 server->noblockcnt ? O_NONBLOCK : 0);
3073 * When mounting SMB root file systems, we do not want to block in
3074 * connect. Otherwise bail out and then let cifs_reconnect() perform
3075 * reconnect failover - if possible.
3077 if (server->noblockcnt && rc == -EINPROGRESS)
3080 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3081 trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
3082 sock_release(socket);
3083 server->ssocket = NULL;
3086 trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
3087 if (sport == htons(RFC1001_PORT))
3088 rc = ip_rfc1001_connect(server);
3094 ip_connect(struct TCP_Server_Info *server)
3097 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3098 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3100 if (server->dstaddr.ss_family == AF_INET6)
3101 sport = &addr6->sin6_port;
3103 sport = &addr->sin_port;
3108 /* try with 445 port at first */
3109 *sport = htons(CIFS_PORT);
3111 rc = generic_ip_connect(server);
3115 /* if it failed, try with 139 port */
3116 *sport = htons(RFC1001_PORT);
3119 return generic_ip_connect(server);
3122 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3123 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3124 struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3127 * If we are reconnecting then should we check to see if
3128 * any requested capabilities changed locally e.g. via
3129 * remount but we can not do much about it here
3130 * if they have (even if we could detect it by the following)
3131 * Perhaps we could add a backpointer to array of sb from tcon
3132 * or if we change to make all sb to same share the same
3133 * sb as NFS - then we only have one backpointer to sb.
3134 * What if we wanted to mount the server share twice once with
3135 * and once without posixacls or posix paths?
3137 __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3139 if (ctx && ctx->no_linux_ext) {
3140 tcon->fsUnixInfo.Capability = 0;
3141 tcon->unix_ext = 0; /* Unix Extensions disabled */
3142 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3145 tcon->unix_ext = 1; /* Unix Extensions supported */
3147 if (!tcon->unix_ext) {
3148 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3152 if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3153 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3154 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3156 * check for reconnect case in which we do not
3157 * want to change the mount behavior if we can avoid it
3161 * turn off POSIX ACL and PATHNAMES if not set
3162 * originally at mount time
3164 if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3165 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3166 if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3167 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3168 cifs_dbg(VFS, "POSIXPATH support change\n");
3169 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3170 } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3171 cifs_dbg(VFS, "possible reconnect error\n");
3172 cifs_dbg(VFS, "server disabled POSIX path support\n");
3176 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3177 cifs_dbg(VFS, "per-share encryption not supported yet\n");
3179 cap &= CIFS_UNIX_CAP_MASK;
3180 if (ctx && ctx->no_psx_acl)
3181 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3182 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3183 cifs_dbg(FYI, "negotiated posix acl support\n");
3185 cifs_sb->mnt_cifs_flags |=
3186 CIFS_MOUNT_POSIXACL;
3189 if (ctx && ctx->posix_paths == 0)
3190 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3191 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3192 cifs_dbg(FYI, "negotiate posix pathnames\n");
3194 cifs_sb->mnt_cifs_flags |=
3195 CIFS_MOUNT_POSIX_PATHS;
3198 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3199 #ifdef CONFIG_CIFS_DEBUG2
3200 if (cap & CIFS_UNIX_FCNTL_CAP)
3201 cifs_dbg(FYI, "FCNTL cap\n");
3202 if (cap & CIFS_UNIX_EXTATTR_CAP)
3203 cifs_dbg(FYI, "EXTATTR cap\n");
3204 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3205 cifs_dbg(FYI, "POSIX path cap\n");
3206 if (cap & CIFS_UNIX_XATTR_CAP)
3207 cifs_dbg(FYI, "XATTR cap\n");
3208 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3209 cifs_dbg(FYI, "POSIX ACL cap\n");
3210 if (cap & CIFS_UNIX_LARGE_READ_CAP)
3211 cifs_dbg(FYI, "very large read cap\n");
3212 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3213 cifs_dbg(FYI, "very large write cap\n");
3214 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3215 cifs_dbg(FYI, "transport encryption cap\n");
3216 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3217 cifs_dbg(FYI, "mandatory transport encryption cap\n");
3218 #endif /* CIFS_DEBUG2 */
3219 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3221 cifs_dbg(FYI, "resetting capabilities failed\n");
3223 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");
3228 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3230 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3232 struct smb3_fs_context *ctx = cifs_sb->ctx;
3234 INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3236 spin_lock_init(&cifs_sb->tlink_tree_lock);
3237 cifs_sb->tlink_tree = RB_ROOT;
3239 cifs_dbg(FYI, "file mode: %04ho dir mode: %04ho\n",
3240 ctx->file_mode, ctx->dir_mode);
3242 /* this is needed for ASCII cp to Unicode converts */
3243 if (ctx->iocharset == NULL) {
3244 /* load_nls_default cannot return null */
3245 cifs_sb->local_nls = load_nls_default();
3247 cifs_sb->local_nls = load_nls(ctx->iocharset);
3248 if (cifs_sb->local_nls == NULL) {
3249 cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3254 ctx->local_nls = cifs_sb->local_nls;
3256 smb3_update_mnt_flags(cifs_sb);
3259 cifs_dbg(FYI, "mounting share using direct i/o\n");
3260 if (ctx->cache_ro) {
3261 cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
3262 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3263 } else if (ctx->cache_rw) {
3264 cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
3265 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
3266 CIFS_MOUNT_RW_CACHE);
3269 if ((ctx->cifs_acl) && (ctx->dynperm))
3270 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3273 cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3274 if (cifs_sb->prepath == NULL)
3276 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3282 /* Release all succeed connections */
3283 static inline void mount_put_conns(struct mount_ctx *mnt_ctx)
3288 cifs_put_tcon(mnt_ctx->tcon);
3289 else if (mnt_ctx->ses)
3290 cifs_put_smb_ses(mnt_ctx->ses);
3291 else if (mnt_ctx->server)
3292 cifs_put_tcp_session(mnt_ctx->server, 0);
3293 mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3294 free_xid(mnt_ctx->xid);
3297 /* Get connections for tcp, ses and tcon */
3298 static int mount_get_conns(struct mount_ctx *mnt_ctx)
3301 struct TCP_Server_Info *server = NULL;
3302 struct cifs_ses *ses = NULL;
3303 struct cifs_tcon *tcon = NULL;
3304 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3305 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3310 /* get a reference to a tcp session */
3311 server = cifs_get_tcp_session(ctx, NULL);
3312 if (IS_ERR(server)) {
3313 rc = PTR_ERR(server);
3318 /* get a reference to a SMB session */
3319 ses = cifs_get_smb_ses(server, ctx);
3326 if ((ctx->persistent == true) && (!(ses->server->capabilities &
3327 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3328 cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3333 /* search for existing tcon to this server share */
3334 tcon = cifs_get_tcon(ses, ctx);
3341 /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3342 if (tcon->posix_extensions)
3343 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3345 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3346 /* tell server which Unix caps we support */
3347 if (cap_unix(tcon->ses)) {
3349 * reset of caps checks mount to see if unix extensions disabled
3350 * for just this mount.
3352 reset_cifs_unix_caps(xid, tcon, cifs_sb, ctx);
3353 spin_lock(&tcon->ses->server->srv_lock);
3354 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3355 (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3356 CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3357 spin_unlock(&tcon->ses->server->srv_lock);
3361 spin_unlock(&tcon->ses->server->srv_lock);
3363 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3364 tcon->unix_ext = 0; /* server does not support them */
3366 /* do not care if a following call succeed - informational */
3367 if (!tcon->pipe && server->ops->qfs_tcon) {
3368 server->ops->qfs_tcon(xid, tcon, cifs_sb);
3369 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3370 if (tcon->fsDevInfo.DeviceCharacteristics &
3371 cpu_to_le32(FILE_READ_ONLY_DEVICE))
3372 cifs_dbg(VFS, "mounted to read only share\n");
3373 else if ((cifs_sb->mnt_cifs_flags &
3374 CIFS_MOUNT_RW_CACHE) == 0)
3375 cifs_dbg(VFS, "read only mount of RW share\n");
3376 /* no need to log a RW mount of a typical RW share */
3381 * Clamp the rsize/wsize mount arguments if they are too big for the server
3382 * and set the rsize/wsize to the negotiated values if not passed in by
3385 if ((cifs_sb->ctx->wsize == 0) ||
3386 (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
3387 cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
3388 if ((cifs_sb->ctx->rsize == 0) ||
3389 (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3390 cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3393 * The cookie is initialized from volume info returned above.
3394 * Inside cifs_fscache_get_super_cookie it checks
3395 * that we do not get super cookie twice.
3397 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
3398 cifs_fscache_get_super_cookie(tcon);
3401 mnt_ctx->server = server;
3403 mnt_ctx->tcon = tcon;
3409 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3410 struct cifs_tcon *tcon)
3412 struct tcon_link *tlink;
3414 /* hang the tcon off of the superblock */
3415 tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3419 tlink->tl_uid = ses->linux_uid;
3420 tlink->tl_tcon = tcon;
3421 tlink->tl_time = jiffies;
3422 set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3423 set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3425 cifs_sb->master_tlink = tlink;
3426 spin_lock(&cifs_sb->tlink_tree_lock);
3427 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3428 spin_unlock(&cifs_sb->tlink_tree_lock);
3430 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3435 #ifdef CONFIG_CIFS_DFS_UPCALL
3436 /* Get unique dfs connections */
3437 static int mount_get_dfs_conns(struct mount_ctx *mnt_ctx)
3441 mnt_ctx->fs_ctx->nosharesock = true;
3442 rc = mount_get_conns(mnt_ctx);
3443 if (mnt_ctx->server) {
3444 cifs_dbg(FYI, "%s: marking tcp session as a dfs connection\n", __func__);
3445 spin_lock(&mnt_ctx->server->srv_lock);
3446 mnt_ctx->server->is_dfs_conn = true;
3447 spin_unlock(&mnt_ctx->server->srv_lock);
3453 * cifs_build_path_to_root returns full path to root when we do not have an
3454 * existing connection (tcon)
3457 build_unc_path_to_root(const struct smb3_fs_context *ctx,
3458 const struct cifs_sb_info *cifs_sb, bool useppath)
3460 char *full_path, *pos;
3461 unsigned int pplen = useppath && ctx->prepath ?
3462 strlen(ctx->prepath) + 1 : 0;
3463 unsigned int unc_len = strnlen(ctx->UNC, MAX_TREE_SIZE + 1);
3465 if (unc_len > MAX_TREE_SIZE)
3466 return ERR_PTR(-EINVAL);
3468 full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
3469 if (full_path == NULL)
3470 return ERR_PTR(-ENOMEM);
3472 memcpy(full_path, ctx->UNC, unc_len);
3473 pos = full_path + unc_len;
3476 *pos = CIFS_DIR_SEP(cifs_sb);
3477 memcpy(pos + 1, ctx->prepath, pplen);
3481 *pos = '\0'; /* add trailing null */
3482 convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
3483 cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
3488 * expand_dfs_referral - Update cifs_sb from dfs referral path
3490 * cifs_sb->ctx->mount_options will be (re-)allocated to a string containing updated options for the
3491 * submount. Otherwise it will be left untouched.
3493 static int expand_dfs_referral(struct mount_ctx *mnt_ctx, const char *full_path,
3494 struct dfs_info3_param *referral)
3497 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3498 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3499 char *fake_devname = NULL, *mdata = NULL;
3501 mdata = cifs_compose_mount_options(cifs_sb->ctx->mount_options, full_path + 1, referral,
3503 if (IS_ERR(mdata)) {
3504 rc = PTR_ERR(mdata);
3508 * We can not clear out the whole structure since we no longer have an explicit
3509 * function to parse a mount-string. Instead we need to clear out the individual
3510 * fields that are no longer valid.
3512 kfree(ctx->prepath);
3513 ctx->prepath = NULL;
3514 rc = cifs_setup_volume_info(ctx, mdata, fake_devname);
3516 kfree(fake_devname);
3517 kfree(cifs_sb->ctx->mount_options);
3518 cifs_sb->ctx->mount_options = mdata;
3524 /* TODO: all callers to this are broken. We are not parsing mount_options here
3525 * we should pass a clone of the original context?
3528 cifs_setup_volume_info(struct smb3_fs_context *ctx, const char *mntopts, const char *devname)
3533 cifs_dbg(FYI, "%s: devname=%s\n", __func__, devname);
3534 rc = smb3_parse_devname(devname, ctx);
3536 cifs_dbg(VFS, "%s: failed to parse %s: %d\n", __func__, devname, rc);
3544 rc = smb3_parse_opt(mntopts, "ip", &ip);
3546 cifs_dbg(VFS, "%s: failed to parse ip options: %d\n", __func__, rc);
3550 rc = cifs_convert_address((struct sockaddr *)&ctx->dstaddr, ip, strlen(ip));
3553 cifs_dbg(VFS, "%s: failed to convert ip address\n", __func__);
3558 if (ctx->nullauth) {
3559 cifs_dbg(FYI, "Anonymous login\n");
3560 kfree(ctx->username);
3561 ctx->username = NULL;
3562 } else if (ctx->username) {
3563 /* BB fixme parse for domain name here */
3564 cifs_dbg(FYI, "Username: %s\n", ctx->username);
3566 cifs_dbg(VFS, "No username specified\n");
3567 /* In userspace mount helper we can get user name from alternate
3568 locations such as env variables and files on disk */
3576 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3578 struct cifs_tcon *tcon,
3579 struct cifs_sb_info *cifs_sb,
3586 int skip = added_treename ? 1 : 0;
3588 sep = CIFS_DIR_SEP(cifs_sb);
3591 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3593 /* skip separators */
3598 /* next separator */
3599 while (*s && *s != sep)
3602 * if the treename is added, we then have to skip the first
3603 * part within the separators
3610 * temporarily null-terminate the path at the end of
3611 * the current component
3615 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3623 * Check if path is remote (i.e. a DFS share).
3625 * Return -EREMOTE if it is, otherwise 0 or -errno.
3627 static int is_path_remote(struct mount_ctx *mnt_ctx)
3630 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3631 struct TCP_Server_Info *server = mnt_ctx->server;
3632 unsigned int xid = mnt_ctx->xid;
3633 struct cifs_tcon *tcon = mnt_ctx->tcon;
3634 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3637 if (!server->ops->is_path_accessible)
3641 * cifs_build_path_to_root works only when we have a valid tcon
3643 full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3644 tcon->Flags & SMB_SHARE_IS_IN_DFS);
3645 if (full_path == NULL)
3648 cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3650 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3652 if (rc != 0 && rc != -EREMOTE)
3655 if (rc != -EREMOTE) {
3656 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3657 cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3659 cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3660 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3670 #ifdef CONFIG_CIFS_DFS_UPCALL
3671 static void set_root_ses(struct mount_ctx *mnt_ctx)
3674 spin_lock(&cifs_tcp_ses_lock);
3675 mnt_ctx->ses->ses_count++;
3676 spin_unlock(&cifs_tcp_ses_lock);
3677 dfs_cache_add_refsrv_session(&mnt_ctx->mount_id, mnt_ctx->ses);
3679 mnt_ctx->root_ses = mnt_ctx->ses;
3682 static int is_dfs_mount(struct mount_ctx *mnt_ctx, bool *isdfs, struct dfs_cache_tgt_list *root_tl)
3685 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3686 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3690 rc = mount_get_conns(mnt_ctx);
3692 * If called with 'nodfs' mount option, then skip DFS resolving. Otherwise unconditionally
3693 * try to get an DFS referral (even cached) to determine whether it is an DFS mount.
3695 * Skip prefix path to provide support for DFS referrals from w2k8 servers which don't seem
3696 * to respond with PATH_NOT_COVERED to requests that include the prefix.
3698 if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
3699 dfs_cache_find(mnt_ctx->xid, mnt_ctx->ses, cifs_sb->local_nls, cifs_remap(cifs_sb),
3700 ctx->UNC + 1, NULL, root_tl)) {
3703 /* Check if it is fully accessible and then mount it */
3704 rc = is_path_remote(mnt_ctx);
3707 else if (rc != -EREMOTE)
3713 static int connect_dfs_target(struct mount_ctx *mnt_ctx, const char *full_path,
3714 const char *ref_path, struct dfs_cache_tgt_iterator *tit)
3717 struct dfs_info3_param ref = {};
3718 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3719 char *oldmnt = cifs_sb->ctx->mount_options;
3721 cifs_dbg(FYI, "%s: full_path=%s ref_path=%s target=%s\n", __func__, full_path, ref_path,
3722 dfs_cache_get_tgt_name(tit));
3724 rc = dfs_cache_get_tgt_referral(ref_path, tit, &ref);
3728 rc = expand_dfs_referral(mnt_ctx, full_path, &ref);
3732 /* Connect to new target only if we were redirected (e.g. mount options changed) */
3733 if (oldmnt != cifs_sb->ctx->mount_options) {
3734 mount_put_conns(mnt_ctx);
3735 rc = mount_get_dfs_conns(mnt_ctx);
3738 if (cifs_is_referral_server(mnt_ctx->tcon, &ref))
3739 set_root_ses(mnt_ctx);
3740 rc = dfs_cache_update_tgthint(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3741 cifs_remap(cifs_sb), ref_path, tit);
3745 free_dfs_info_param(&ref);
3749 static int connect_dfs_root(struct mount_ctx *mnt_ctx, struct dfs_cache_tgt_list *root_tl)
3753 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3754 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3755 struct dfs_cache_tgt_iterator *tit;
3757 /* Put initial connections as they might be shared with other mounts. We need unique dfs
3758 * connections per mount to properly failover, so mount_get_dfs_conns() must be used from
3761 mount_put_conns(mnt_ctx);
3762 mount_get_dfs_conns(mnt_ctx);
3763 set_root_ses(mnt_ctx);
3765 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3766 if (IS_ERR(full_path))
3767 return PTR_ERR(full_path);
3769 mnt_ctx->origin_fullpath = dfs_cache_canonical_path(ctx->UNC, cifs_sb->local_nls,
3770 cifs_remap(cifs_sb));
3771 if (IS_ERR(mnt_ctx->origin_fullpath)) {
3772 rc = PTR_ERR(mnt_ctx->origin_fullpath);
3773 mnt_ctx->origin_fullpath = NULL;
3777 /* Try all dfs root targets */
3778 for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(root_tl);
3779 tit; tit = dfs_cache_get_next_tgt(root_tl, tit)) {
3780 rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->origin_fullpath + 1, tit);
3782 mnt_ctx->leaf_fullpath = kstrdup(mnt_ctx->origin_fullpath, GFP_KERNEL);
3783 if (!mnt_ctx->leaf_fullpath)
3794 static int __follow_dfs_link(struct mount_ctx *mnt_ctx)
3797 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3798 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3800 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3801 struct dfs_cache_tgt_iterator *tit;
3803 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3804 if (IS_ERR(full_path))
3805 return PTR_ERR(full_path);
3807 kfree(mnt_ctx->leaf_fullpath);
3808 mnt_ctx->leaf_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3809 cifs_remap(cifs_sb));
3810 if (IS_ERR(mnt_ctx->leaf_fullpath)) {
3811 rc = PTR_ERR(mnt_ctx->leaf_fullpath);
3812 mnt_ctx->leaf_fullpath = NULL;
3816 /* Get referral from dfs link */
3817 rc = dfs_cache_find(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3818 cifs_remap(cifs_sb), mnt_ctx->leaf_fullpath + 1, NULL, &tl);
3822 /* Try all dfs link targets. If an I/O fails from currently connected DFS target with an
3823 * error other than STATUS_PATH_NOT_COVERED (-EREMOTE), then retry it from other targets as
3824 * specified in MS-DFSC "3.1.5.2 I/O Operation to Target Fails with an Error Other Than
3825 * STATUS_PATH_NOT_COVERED."
3827 for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(&tl);
3828 tit; tit = dfs_cache_get_next_tgt(&tl, tit)) {
3829 rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->leaf_fullpath + 1, tit);
3831 rc = is_path_remote(mnt_ctx);
3832 if (!rc || rc == -EREMOTE)
3839 dfs_cache_free_tgts(&tl);
3843 static int follow_dfs_link(struct mount_ctx *mnt_ctx)
3846 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3847 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3851 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3852 if (IS_ERR(full_path))
3853 return PTR_ERR(full_path);
3855 kfree(mnt_ctx->origin_fullpath);
3856 mnt_ctx->origin_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3857 cifs_remap(cifs_sb));
3860 if (IS_ERR(mnt_ctx->origin_fullpath)) {
3861 rc = PTR_ERR(mnt_ctx->origin_fullpath);
3862 mnt_ctx->origin_fullpath = NULL;
3867 rc = __follow_dfs_link(mnt_ctx);
3868 if (!rc || rc != -EREMOTE)
3870 } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
3875 /* Set up DFS referral paths for failover */
3876 static void setup_server_referral_paths(struct mount_ctx *mnt_ctx)
3878 struct TCP_Server_Info *server = mnt_ctx->server;
3880 mutex_lock(&server->refpath_lock);
3881 server->origin_fullpath = mnt_ctx->origin_fullpath;
3882 server->leaf_fullpath = mnt_ctx->leaf_fullpath;
3883 server->current_fullpath = mnt_ctx->leaf_fullpath;
3884 mutex_unlock(&server->refpath_lock);
3885 mnt_ctx->origin_fullpath = mnt_ctx->leaf_fullpath = NULL;
3888 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3891 struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3892 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3895 rc = is_dfs_mount(&mnt_ctx, &isdfs, &tl);
3901 /* proceed as DFS mount */
3902 uuid_gen(&mnt_ctx.mount_id);
3903 rc = connect_dfs_root(&mnt_ctx, &tl);
3904 dfs_cache_free_tgts(&tl);
3909 rc = is_path_remote(&mnt_ctx);
3911 rc = follow_dfs_link(&mnt_ctx);
3915 setup_server_referral_paths(&mnt_ctx);
3917 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3918 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3920 cifs_autodisable_serverino(cifs_sb);
3922 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3923 * that have different prefix paths.
3925 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3926 kfree(cifs_sb->prepath);
3927 cifs_sb->prepath = ctx->prepath;
3928 ctx->prepath = NULL;
3929 uuid_copy(&cifs_sb->dfs_mount_id, &mnt_ctx.mount_id);
3932 cifs_try_adding_channels(cifs_sb, mnt_ctx.ses);
3933 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3937 free_xid(mnt_ctx.xid);
3941 dfs_cache_put_refsrv_sessions(&mnt_ctx.mount_id);
3942 kfree(mnt_ctx.origin_fullpath);
3943 kfree(mnt_ctx.leaf_fullpath);
3944 mount_put_conns(&mnt_ctx);
3948 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3951 struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3953 rc = mount_get_conns(&mnt_ctx);
3958 rc = is_path_remote(&mnt_ctx);
3965 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3969 free_xid(mnt_ctx.xid);
3973 mount_put_conns(&mnt_ctx);
3979 * Issue a TREE_CONNECT request.
3982 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3983 const char *tree, struct cifs_tcon *tcon,
3984 const struct nls_table *nls_codepage)
3986 struct smb_hdr *smb_buffer;
3987 struct smb_hdr *smb_buffer_response;
3990 unsigned char *bcc_ptr;
3993 __u16 bytes_left, count;
3998 smb_buffer = cifs_buf_get();
3999 if (smb_buffer == NULL)
4002 smb_buffer_response = smb_buffer;
4004 header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
4005 NULL /*no tid */ , 4 /*wct */ );
4007 smb_buffer->Mid = get_next_mid(ses->server);
4008 smb_buffer->Uid = ses->Suid;
4009 pSMB = (TCONX_REQ *) smb_buffer;
4010 pSMBr = (TCONX_RSP *) smb_buffer_response;
4012 pSMB->AndXCommand = 0xFF;
4013 pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
4014 bcc_ptr = &pSMB->Password[0];
4016 pSMB->PasswordLength = cpu_to_le16(1); /* minimum */
4017 *bcc_ptr = 0; /* password is null byte */
4018 bcc_ptr++; /* skip password */
4019 /* already aligned so no need to do it below */
4021 if (ses->server->sign)
4022 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
4024 if (ses->capabilities & CAP_STATUS32) {
4025 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
4027 if (ses->capabilities & CAP_DFS) {
4028 smb_buffer->Flags2 |= SMBFLG2_DFS;
4030 if (ses->capabilities & CAP_UNICODE) {
4031 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
4033 cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
4034 6 /* max utf8 char length in bytes */ *
4035 (/* server len*/ + 256 /* share len */), nls_codepage);
4036 bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */
4037 bcc_ptr += 2; /* skip trailing null */
4038 } else { /* ASCII */
4039 strcpy(bcc_ptr, tree);
4040 bcc_ptr += strlen(tree) + 1;
4042 strcpy(bcc_ptr, "?????");
4043 bcc_ptr += strlen("?????");
4045 count = bcc_ptr - &pSMB->Password[0];
4046 be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
4047 pSMB->ByteCount = cpu_to_le16(count);
4049 rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
4052 /* above now done in SendReceive */
4056 tcon->tid = smb_buffer_response->Tid;
4057 bcc_ptr = pByteArea(smb_buffer_response);
4058 bytes_left = get_bcc(smb_buffer_response);
4059 length = strnlen(bcc_ptr, bytes_left - 2);
4060 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
4066 /* skip service field (NB: this field is always ASCII) */
4068 if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
4069 (bcc_ptr[2] == 'C')) {
4070 cifs_dbg(FYI, "IPC connection\n");
4074 } else if (length == 2) {
4075 if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
4076 /* the most common case */
4077 cifs_dbg(FYI, "disk share connection\n");
4080 bcc_ptr += length + 1;
4081 bytes_left -= (length + 1);
4082 strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
4084 /* mostly informational -- no need to fail on error here */
4085 kfree(tcon->nativeFileSystem);
4086 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
4087 bytes_left, is_unicode,
4090 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
4092 if ((smb_buffer_response->WordCount == 3) ||
4093 (smb_buffer_response->WordCount == 7))
4094 /* field is in same location */
4095 tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
4098 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
4101 cifs_buf_release(smb_buffer);
4105 static void delayed_free(struct rcu_head *p)
4107 struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
4109 unload_nls(cifs_sb->local_nls);
4110 smb3_cleanup_fs_context(cifs_sb->ctx);
4115 cifs_umount(struct cifs_sb_info *cifs_sb)
4117 struct rb_root *root = &cifs_sb->tlink_tree;
4118 struct rb_node *node;
4119 struct tcon_link *tlink;
4121 cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
4123 spin_lock(&cifs_sb->tlink_tree_lock);
4124 while ((node = rb_first(root))) {
4125 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4126 cifs_get_tlink(tlink);
4127 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4128 rb_erase(node, root);
4130 spin_unlock(&cifs_sb->tlink_tree_lock);
4131 cifs_put_tlink(tlink);
4132 spin_lock(&cifs_sb->tlink_tree_lock);
4134 spin_unlock(&cifs_sb->tlink_tree_lock);
4136 kfree(cifs_sb->prepath);
4137 #ifdef CONFIG_CIFS_DFS_UPCALL
4138 dfs_cache_put_refsrv_sessions(&cifs_sb->dfs_mount_id);
4140 call_rcu(&cifs_sb->rcu, delayed_free);
4144 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
4145 struct TCP_Server_Info *server)
4149 if (!server->ops->need_neg || !server->ops->negotiate)
4152 /* only send once per connect */
4153 spin_lock(&server->srv_lock);
4154 if (server->tcpStatus != CifsGood &&
4155 server->tcpStatus != CifsNew &&
4156 server->tcpStatus != CifsNeedNegotiate) {
4157 spin_unlock(&server->srv_lock);
4161 if (!server->ops->need_neg(server) &&
4162 server->tcpStatus == CifsGood) {
4163 spin_unlock(&server->srv_lock);
4167 server->tcpStatus = CifsInNegotiate;
4168 spin_unlock(&server->srv_lock);
4170 rc = server->ops->negotiate(xid, ses, server);
4172 spin_lock(&server->srv_lock);
4173 if (server->tcpStatus == CifsInNegotiate)
4174 server->tcpStatus = CifsGood;
4177 spin_unlock(&server->srv_lock);
4179 spin_lock(&server->srv_lock);
4180 if (server->tcpStatus == CifsInNegotiate)
4181 server->tcpStatus = CifsNeedNegotiate;
4182 spin_unlock(&server->srv_lock);
4189 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
4190 struct TCP_Server_Info *server,
4191 struct nls_table *nls_info)
4194 struct TCP_Server_Info *pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
4195 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&pserver->dstaddr;
4196 struct sockaddr_in *addr = (struct sockaddr_in *)&pserver->dstaddr;
4197 bool is_binding = false;
4199 spin_lock(&ses->ses_lock);
4200 cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
4201 __func__, ses->chans_need_reconnect);
4203 if (ses->ses_status != SES_GOOD &&
4204 ses->ses_status != SES_NEW &&
4205 ses->ses_status != SES_NEED_RECON) {
4206 spin_unlock(&ses->ses_lock);
4210 /* only send once per connect */
4211 spin_lock(&ses->chan_lock);
4212 if (CIFS_ALL_CHANS_GOOD(ses)) {
4213 if (ses->ses_status == SES_NEED_RECON)
4214 ses->ses_status = SES_GOOD;
4215 spin_unlock(&ses->chan_lock);
4216 spin_unlock(&ses->ses_lock);
4220 cifs_chan_set_in_reconnect(ses, server);
4221 is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
4222 spin_unlock(&ses->chan_lock);
4225 ses->ses_status = SES_IN_SETUP;
4227 /* force iface_list refresh */
4228 ses->iface_last_update = 0;
4230 spin_unlock(&ses->ses_lock);
4232 /* update ses ip_addr only for primary chan */
4233 if (server == pserver) {
4234 if (server->dstaddr.ss_family == AF_INET6)
4235 scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
4237 scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
4241 ses->capabilities = server->capabilities;
4242 if (!linuxExtEnabled)
4243 ses->capabilities &= (~server->vals->cap_unix);
4245 if (ses->auth_key.response) {
4246 cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
4247 ses->auth_key.response);
4248 kfree_sensitive(ses->auth_key.response);
4249 ses->auth_key.response = NULL;
4250 ses->auth_key.len = 0;
4254 cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
4255 server->sec_mode, server->capabilities, server->timeAdj);
4257 if (server->ops->sess_setup)
4258 rc = server->ops->sess_setup(xid, ses, server, nls_info);
4261 cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
4262 spin_lock(&ses->ses_lock);
4263 if (ses->ses_status == SES_IN_SETUP)
4264 ses->ses_status = SES_NEED_RECON;
4265 spin_lock(&ses->chan_lock);
4266 cifs_chan_clear_in_reconnect(ses, server);
4267 spin_unlock(&ses->chan_lock);
4268 spin_unlock(&ses->ses_lock);
4270 spin_lock(&ses->ses_lock);
4271 if (ses->ses_status == SES_IN_SETUP)
4272 ses->ses_status = SES_GOOD;
4273 spin_lock(&ses->chan_lock);
4274 cifs_chan_clear_in_reconnect(ses, server);
4275 cifs_chan_clear_need_reconnect(ses, server);
4276 spin_unlock(&ses->chan_lock);
4277 spin_unlock(&ses->ses_lock);
4284 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
4286 ctx->sectype = ses->sectype;
4288 /* krb5 is special, since we don't need username or pw */
4289 if (ctx->sectype == Kerberos)
4292 return cifs_set_cifscreds(ctx, ses);
4295 static struct cifs_tcon *
4296 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4299 struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
4300 struct cifs_ses *ses;
4301 struct cifs_tcon *tcon = NULL;
4302 struct smb3_fs_context *ctx;
4304 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
4306 return ERR_PTR(-ENOMEM);
4308 ctx->local_nls = cifs_sb->local_nls;
4309 ctx->linux_uid = fsuid;
4310 ctx->cred_uid = fsuid;
4311 ctx->UNC = master_tcon->tree_name;
4312 ctx->retry = master_tcon->retry;
4313 ctx->nocase = master_tcon->nocase;
4314 ctx->nohandlecache = master_tcon->nohandlecache;
4315 ctx->local_lease = master_tcon->local_lease;
4316 ctx->no_lease = master_tcon->no_lease;
4317 ctx->resilient = master_tcon->use_resilient;
4318 ctx->persistent = master_tcon->use_persistent;
4319 ctx->handle_timeout = master_tcon->handle_timeout;
4320 ctx->no_linux_ext = !master_tcon->unix_ext;
4321 ctx->linux_ext = master_tcon->posix_extensions;
4322 ctx->sectype = master_tcon->ses->sectype;
4323 ctx->sign = master_tcon->ses->sign;
4324 ctx->seal = master_tcon->seal;
4325 ctx->witness = master_tcon->use_witness;
4327 rc = cifs_set_vol_auth(ctx, master_tcon->ses);
4333 /* get a reference for the same TCP session */
4334 spin_lock(&cifs_tcp_ses_lock);
4335 ++master_tcon->ses->server->srv_count;
4336 spin_unlock(&cifs_tcp_ses_lock);
4338 ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4340 tcon = (struct cifs_tcon *)ses;
4341 cifs_put_tcp_session(master_tcon->ses->server, 0);
4345 tcon = cifs_get_tcon(ses, ctx);
4347 cifs_put_smb_ses(ses);
4351 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4353 reset_cifs_unix_caps(0, tcon, NULL, ctx);
4354 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4357 kfree(ctx->username);
4358 kfree_sensitive(ctx->password);
4365 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4367 return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4370 /* find and return a tlink with given uid */
4371 static struct tcon_link *
4372 tlink_rb_search(struct rb_root *root, kuid_t uid)
4374 struct rb_node *node = root->rb_node;
4375 struct tcon_link *tlink;
4378 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4380 if (uid_gt(tlink->tl_uid, uid))
4381 node = node->rb_left;
4382 else if (uid_lt(tlink->tl_uid, uid))
4383 node = node->rb_right;
4390 /* insert a tcon_link into the tree */
4392 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4394 struct rb_node **new = &(root->rb_node), *parent = NULL;
4395 struct tcon_link *tlink;
4398 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4401 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4402 new = &((*new)->rb_left);
4404 new = &((*new)->rb_right);
4407 rb_link_node(&new_tlink->tl_rbnode, parent, new);
4408 rb_insert_color(&new_tlink->tl_rbnode, root);
4412 * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4415 * If the superblock doesn't refer to a multiuser mount, then just return
4416 * the master tcon for the mount.
4418 * First, search the rbtree for an existing tcon for this fsuid. If one
4419 * exists, then check to see if it's pending construction. If it is then wait
4420 * for construction to complete. Once it's no longer pending, check to see if
4421 * it failed and either return an error or retry construction, depending on
4424 * If one doesn't exist then insert a new tcon_link struct into the tree and
4425 * try to construct a new one.
4428 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4431 kuid_t fsuid = current_fsuid();
4432 struct tcon_link *tlink, *newtlink;
4434 if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4435 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4437 spin_lock(&cifs_sb->tlink_tree_lock);
4438 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4440 cifs_get_tlink(tlink);
4441 spin_unlock(&cifs_sb->tlink_tree_lock);
4443 if (tlink == NULL) {
4444 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4445 if (newtlink == NULL)
4446 return ERR_PTR(-ENOMEM);
4447 newtlink->tl_uid = fsuid;
4448 newtlink->tl_tcon = ERR_PTR(-EACCES);
4449 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4450 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4451 cifs_get_tlink(newtlink);
4453 spin_lock(&cifs_sb->tlink_tree_lock);
4454 /* was one inserted after previous search? */
4455 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4457 cifs_get_tlink(tlink);
4458 spin_unlock(&cifs_sb->tlink_tree_lock);
4460 goto wait_for_construction;
4463 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4464 spin_unlock(&cifs_sb->tlink_tree_lock);
4466 wait_for_construction:
4467 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4468 TASK_INTERRUPTIBLE);
4470 cifs_put_tlink(tlink);
4471 return ERR_PTR(-ERESTARTSYS);
4474 /* if it's good, return it */
4475 if (!IS_ERR(tlink->tl_tcon))
4478 /* return error if we tried this already recently */
4479 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4480 cifs_put_tlink(tlink);
4481 return ERR_PTR(-EACCES);
4484 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4485 goto wait_for_construction;
4488 tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4489 clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4490 wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4492 if (IS_ERR(tlink->tl_tcon)) {
4493 cifs_put_tlink(tlink);
4494 return ERR_PTR(-EACCES);
4501 * periodic workqueue job that scans tcon_tree for a superblock and closes
4505 cifs_prune_tlinks(struct work_struct *work)
4507 struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4509 struct rb_root *root = &cifs_sb->tlink_tree;
4510 struct rb_node *node;
4511 struct rb_node *tmp;
4512 struct tcon_link *tlink;
4515 * Because we drop the spinlock in the loop in order to put the tlink
4516 * it's not guarded against removal of links from the tree. The only
4517 * places that remove entries from the tree are this function and
4518 * umounts. Because this function is non-reentrant and is canceled
4519 * before umount can proceed, this is safe.
4521 spin_lock(&cifs_sb->tlink_tree_lock);
4522 node = rb_first(root);
4523 while (node != NULL) {
4525 node = rb_next(tmp);
4526 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4528 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4529 atomic_read(&tlink->tl_count) != 0 ||
4530 time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4533 cifs_get_tlink(tlink);
4534 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4535 rb_erase(tmp, root);
4537 spin_unlock(&cifs_sb->tlink_tree_lock);
4538 cifs_put_tlink(tlink);
4539 spin_lock(&cifs_sb->tlink_tree_lock);
4541 spin_unlock(&cifs_sb->tlink_tree_lock);
4543 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4547 #ifdef CONFIG_CIFS_DFS_UPCALL
4548 /* Update dfs referral path of superblock */
4549 static int update_server_fullpath(struct TCP_Server_Info *server, struct cifs_sb_info *cifs_sb,
4553 size_t len = strlen(target);
4554 char *refpath, *npath;
4556 if (unlikely(len < 2 || *target != '\\'))
4559 if (target[1] == '\\') {
4561 refpath = kmalloc(len, GFP_KERNEL);
4565 scnprintf(refpath, len, "%s", target);
4567 len += sizeof("\\");
4568 refpath = kmalloc(len, GFP_KERNEL);
4572 scnprintf(refpath, len, "\\%s", target);
4575 npath = dfs_cache_canonical_path(refpath, cifs_sb->local_nls, cifs_remap(cifs_sb));
4578 if (IS_ERR(npath)) {
4579 rc = PTR_ERR(npath);
4581 mutex_lock(&server->refpath_lock);
4582 kfree(server->leaf_fullpath);
4583 server->leaf_fullpath = npath;
4584 mutex_unlock(&server->refpath_lock);
4585 server->current_fullpath = server->leaf_fullpath;
4590 static int target_share_matches_server(struct TCP_Server_Info *server, const char *tcp_host,
4591 size_t tcp_host_len, char *share, bool *target_match)
4594 const char *dfs_host;
4595 size_t dfs_host_len;
4597 *target_match = true;
4598 extract_unc_hostname(share, &dfs_host, &dfs_host_len);
4600 /* Check if hostnames or addresses match */
4601 if (dfs_host_len != tcp_host_len || strncasecmp(dfs_host, tcp_host, dfs_host_len) != 0) {
4602 cifs_dbg(FYI, "%s: %.*s doesn't match %.*s\n", __func__, (int)dfs_host_len,
4603 dfs_host, (int)tcp_host_len, tcp_host);
4604 rc = match_target_ip(server, dfs_host, dfs_host_len, target_match);
4606 cifs_dbg(VFS, "%s: failed to match target ip: %d\n", __func__, rc);
4611 static int __tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4612 struct cifs_sb_info *cifs_sb, char *tree, bool islink,
4613 struct dfs_cache_tgt_list *tl)
4616 struct TCP_Server_Info *server = tcon->ses->server;
4617 const struct smb_version_operations *ops = server->ops;
4618 struct cifs_tcon *ipc = tcon->ses->tcon_ipc;
4619 char *share = NULL, *prefix = NULL;
4620 const char *tcp_host;
4621 size_t tcp_host_len;
4622 struct dfs_cache_tgt_iterator *tit;
4625 extract_unc_hostname(server->hostname, &tcp_host, &tcp_host_len);
4627 tit = dfs_cache_get_tgt_iterator(tl);
4633 /* Try to tree connect to all dfs targets */
4634 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
4635 const char *target = dfs_cache_get_tgt_name(tit);
4636 struct dfs_cache_tgt_list ntl = DFS_CACHE_TGT_LIST_INIT(ntl);
4640 share = prefix = NULL;
4642 /* Check if share matches with tcp ses */
4643 rc = dfs_cache_get_tgt_share(server->current_fullpath + 1, tit, &share, &prefix);
4645 cifs_dbg(VFS, "%s: failed to parse target share: %d\n", __func__, rc);
4649 rc = target_share_matches_server(server, tcp_host, tcp_host_len, share,
4653 if (!target_match) {
4658 if (ipc->need_reconnect) {
4659 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4660 rc = ops->tree_connect(xid, ipc->ses, tree, ipc, cifs_sb->local_nls);
4665 scnprintf(tree, MAX_TREE_SIZE, "\\%s", share);
4667 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4671 * If no dfs referrals were returned from link target, then just do a TREE_CONNECT
4672 * to it. Otherwise, cache the dfs referral and then mark current tcp ses for
4673 * reconnect so either the demultiplex thread or the echo worker will reconnect to
4674 * newly resolved target.
4676 if (dfs_cache_find(xid, tcon->ses, cifs_sb->local_nls, cifs_remap(cifs_sb), target,
4678 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4681 rc = dfs_cache_noreq_update_tgthint(server->current_fullpath + 1, tit);
4683 rc = cifs_update_super_prepath(cifs_sb, prefix);
4685 /* Target is another dfs share */
4686 rc = update_server_fullpath(server, cifs_sb, target);
4687 dfs_cache_free_tgts(tl);
4691 list_replace_init(&ntl.tl_list, &tl->tl_list);
4693 dfs_cache_free_tgts(&ntl);
4705 static int tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4706 struct cifs_sb_info *cifs_sb, char *tree, bool islink,
4707 struct dfs_cache_tgt_list *tl)
4711 struct TCP_Server_Info *server = tcon->ses->server;
4714 rc = __tree_connect_dfs_target(xid, tcon, cifs_sb, tree, islink, tl);
4715 if (!rc || rc != -EREMOTE)
4717 } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
4719 * If we couldn't tree connect to any targets from last referral path, then retry from
4720 * original referral path.
4722 if (rc && server->current_fullpath != server->origin_fullpath) {
4723 server->current_fullpath = server->origin_fullpath;
4724 cifs_signal_cifsd_for_reconnect(server, true);
4727 dfs_cache_free_tgts(tl);
4731 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4734 struct TCP_Server_Info *server = tcon->ses->server;
4735 const struct smb_version_operations *ops = server->ops;
4736 struct super_block *sb = NULL;
4737 struct cifs_sb_info *cifs_sb;
4738 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
4740 struct dfs_info3_param ref = {0};
4742 /* only send once per connect */
4743 spin_lock(&tcon->tc_lock);
4744 if (tcon->ses->ses_status != SES_GOOD ||
4745 (tcon->status != TID_NEW &&
4746 tcon->status != TID_NEED_TCON)) {
4747 spin_unlock(&tcon->tc_lock);
4750 tcon->status = TID_IN_TCON;
4751 spin_unlock(&tcon->tc_lock);
4753 tree = kzalloc(MAX_TREE_SIZE, GFP_KERNEL);
4760 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4761 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, nlsc);
4765 sb = cifs_get_tcp_super(server);
4768 cifs_dbg(VFS, "%s: could not find superblock: %d\n", __func__, rc);
4772 cifs_sb = CIFS_SB(sb);
4774 /* If it is not dfs or there was no cached dfs referral, then reconnect to same share */
4775 if (!server->current_fullpath ||
4776 dfs_cache_noreq_find(server->current_fullpath + 1, &ref, &tl)) {
4777 rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name, tcon, cifs_sb->local_nls);
4781 rc = tree_connect_dfs_target(xid, tcon, cifs_sb, tree, ref.server_type == DFS_TYPE_LINK,
4783 free_dfs_info_param(&ref);
4787 cifs_put_tcp_super(sb);
4790 spin_lock(&tcon->tc_lock);
4791 if (tcon->status == TID_IN_TCON)
4792 tcon->status = TID_NEED_TCON;
4793 spin_unlock(&tcon->tc_lock);
4795 spin_lock(&tcon->tc_lock);
4796 if (tcon->status == TID_IN_TCON)
4797 tcon->status = TID_GOOD;
4798 spin_unlock(&tcon->tc_lock);
4799 tcon->need_reconnect = false;
4805 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4808 const struct smb_version_operations *ops = tcon->ses->server->ops;
4810 /* only send once per connect */
4811 spin_lock(&tcon->tc_lock);
4812 if (tcon->ses->ses_status != SES_GOOD ||
4813 (tcon->status != TID_NEW &&
4814 tcon->status != TID_NEED_TCON)) {
4815 spin_unlock(&tcon->tc_lock);
4818 tcon->status = TID_IN_TCON;
4819 spin_unlock(&tcon->tc_lock);
4821 rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name, tcon, nlsc);
4823 spin_lock(&tcon->tc_lock);
4824 if (tcon->status == TID_IN_TCON)
4825 tcon->status = TID_NEED_TCON;
4826 spin_unlock(&tcon->tc_lock);
4828 spin_lock(&tcon->tc_lock);
4829 if (tcon->status == TID_IN_TCON)
4830 tcon->status = TID_GOOD;
4831 tcon->need_reconnect = false;
4832 spin_unlock(&tcon->tc_lock);