1 // SPDX-License-Identifier: LGPL-2.1
4 * Copyright (C) International Business Machines Corp., 2002,2011
5 * Author(s): Steve French (sfrench@us.ibm.com)
10 #include <linux/string.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/signal.h>
13 #include <linux/list.h>
14 #include <linux/wait.h>
15 #include <linux/slab.h>
16 #include <linux/pagemap.h>
17 #include <linux/ctype.h>
18 #include <linux/utsname.h>
19 #include <linux/mempool.h>
20 #include <linux/delay.h>
21 #include <linux/completion.h>
22 #include <linux/kthread.h>
23 #include <linux/pagevec.h>
24 #include <linux/freezer.h>
25 #include <linux/namei.h>
26 #include <linux/uuid.h>
27 #include <linux/uaccess.h>
28 #include <asm/processor.h>
29 #include <linux/inet.h>
30 #include <linux/module.h>
31 #include <keys/user-type.h>
33 #include <linux/parser.h>
34 #include <linux/bvec.h>
37 #include "cifsproto.h"
38 #include "cifs_unicode.h"
39 #include "cifs_debug.h"
40 #include "cifs_fs_sb.h"
43 #include "rfc1002pdu.h"
45 #include "smb2proto.h"
46 #include "smbdirect.h"
47 #include "dns_resolve.h"
48 #ifdef CONFIG_CIFS_DFS_UPCALL
49 #include "dfs_cache.h"
51 #include "fs_context.h"
54 extern mempool_t *cifs_req_poolp;
55 extern bool disable_legacy_dialects;
57 /* FIXME: should these be tunable? */
58 #define TLINK_ERROR_EXPIRE (1 * HZ)
59 #define TLINK_IDLE_EXPIRE (600 * HZ)
61 /* Drop the connection to not overload the server */
62 #define NUM_STATUS_IO_TIMEOUT 5
65 struct cifs_sb_info *cifs_sb;
66 struct smb3_fs_context *fs_ctx;
68 struct TCP_Server_Info *server;
70 struct cifs_tcon *tcon;
71 #ifdef CONFIG_CIFS_DFS_UPCALL
72 struct cifs_ses *root_ses;
74 char *origin_fullpath, *leaf_fullpath;
78 static int ip_connect(struct TCP_Server_Info *server);
79 static int generic_ip_connect(struct TCP_Server_Info *server);
80 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
81 static void cifs_prune_tlinks(struct work_struct *work);
84 * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
85 * get their ip addresses changed at some point.
87 * This should be called with server->srv_mutex held.
89 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
93 char *unc, *ipaddr = NULL;
95 unsigned long ttl = SMB_DNS_RESOLVE_INTERVAL_DEFAULT;
97 if (!server->hostname)
100 len = strlen(server->hostname) + 3;
102 unc = kmalloc(len, GFP_KERNEL);
104 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
107 scnprintf(unc, len, "\\\\%s", server->hostname);
109 rc = dns_resolve_server_name_to_ip(unc, &ipaddr, &expiry);
113 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
114 __func__, server->hostname, rc);
115 goto requeue_resolve;
118 spin_lock(&cifs_tcp_ses_lock);
119 rc = cifs_convert_address((struct sockaddr *)&server->dstaddr, ipaddr,
121 spin_unlock(&cifs_tcp_ses_lock);
124 /* rc == 1 means success here */
126 now = ktime_get_real_seconds();
127 if (expiry && expiry > now)
129 * To make sure we don't use the cached entry, retry 1s
132 ttl = max_t(unsigned long, expiry - now, SMB_DNS_RESOLVE_INTERVAL_MIN) + 1;
137 cifs_dbg(FYI, "%s: next dns resolution scheduled for %lu seconds in the future\n",
139 mod_delayed_work(cifsiod_wq, &server->resolve, (ttl * HZ));
145 static void cifs_resolve_server(struct work_struct *work)
148 struct TCP_Server_Info *server = container_of(work,
149 struct TCP_Server_Info, resolve.work);
151 mutex_lock(&server->srv_mutex);
154 * Resolve the hostname again to make sure that IP address is up-to-date.
156 rc = reconn_set_ipaddr_from_hostname(server);
158 cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
162 mutex_unlock(&server->srv_mutex);
166 * Mark all sessions and tcons for reconnect.
168 * @server needs to be previously set to CifsNeedReconnect.
172 cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server,
173 bool mark_smb_session)
175 unsigned int num_sessions = 0;
176 struct cifs_ses *ses;
177 struct cifs_tcon *tcon;
178 struct mid_q_entry *mid, *nmid;
179 struct list_head retry_list;
180 struct TCP_Server_Info *pserver;
183 server->max_read = 0;
185 cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
186 trace_smb3_reconnect(server->CurrentMid, server->conn_id, server->hostname);
188 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
189 * are not used until reconnected.
191 cifs_dbg(FYI, "%s: marking sessions and tcons for reconnect\n", __func__);
193 /* If server is a channel, select the primary channel */
194 pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
196 spin_lock(&cifs_tcp_ses_lock);
197 list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
198 spin_lock(&ses->chan_lock);
199 if (!mark_smb_session && cifs_chan_needs_reconnect(ses, server))
202 if (mark_smb_session)
203 CIFS_SET_ALL_CHANS_NEED_RECONNECT(ses);
205 cifs_chan_set_need_reconnect(ses, server);
207 /* If all channels need reconnect, then tcon needs reconnect */
208 if (!mark_smb_session && !CIFS_ALL_CHANS_NEED_RECONNECT(ses))
213 list_for_each_entry(tcon, &ses->tcon_list, tcon_list)
214 tcon->need_reconnect = true;
216 ses->tcon_ipc->need_reconnect = true;
219 spin_unlock(&ses->chan_lock);
221 spin_unlock(&cifs_tcp_ses_lock);
223 if (num_sessions == 0)
226 * before reconnecting the tcp session, mark the smb session (uid)
227 * and the tid bad so they are not used until reconnected
229 cifs_dbg(FYI, "%s: marking sessions and tcons for reconnect\n",
231 /* do not want to be sending data on a socket we are freeing */
232 cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
233 mutex_lock(&server->srv_mutex);
234 if (server->ssocket) {
235 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
236 server->ssocket->flags);
237 kernel_sock_shutdown(server->ssocket, SHUT_WR);
238 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
239 server->ssocket->flags);
240 sock_release(server->ssocket);
241 server->ssocket = NULL;
243 server->sequence_number = 0;
244 server->session_estab = false;
245 kfree(server->session_key.response);
246 server->session_key.response = NULL;
247 server->session_key.len = 0;
248 server->lstrp = jiffies;
250 /* mark submitted MIDs for retry and issue callback */
251 INIT_LIST_HEAD(&retry_list);
252 cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
253 spin_lock(&GlobalMid_Lock);
254 list_for_each_entry_safe(mid, nmid, &server->pending_mid_q, qhead) {
255 kref_get(&mid->refcount);
256 if (mid->mid_state == MID_REQUEST_SUBMITTED)
257 mid->mid_state = MID_RETRY_NEEDED;
258 list_move(&mid->qhead, &retry_list);
259 mid->mid_flags |= MID_DELETED;
261 spin_unlock(&GlobalMid_Lock);
262 mutex_unlock(&server->srv_mutex);
264 cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
265 list_for_each_entry_safe(mid, nmid, &retry_list, qhead) {
266 list_del_init(&mid->qhead);
268 cifs_mid_q_entry_release(mid);
271 if (cifs_rdma_enabled(server)) {
272 mutex_lock(&server->srv_mutex);
273 smbd_destroy(server);
274 mutex_unlock(&server->srv_mutex);
278 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
280 spin_lock(&cifs_tcp_ses_lock);
281 server->nr_targets = num_targets;
282 if (server->tcpStatus == CifsExiting) {
283 /* the demux thread will exit normally next time through the loop */
284 spin_unlock(&cifs_tcp_ses_lock);
285 wake_up(&server->response_q);
288 server->tcpStatus = CifsNeedReconnect;
289 spin_unlock(&cifs_tcp_ses_lock);
294 * cifs tcp session reconnection
296 * mark tcp session as reconnecting so temporarily locked
297 * mark all smb sessions as reconnecting for tcp session
298 * reconnect tcp session
299 * wake up waiters on reconnection? - (not needed currently)
301 * if mark_smb_session is passed as true, unconditionally mark
302 * the smb session (and tcon) for reconnect as well. This value
303 * doesn't really matter for non-multichannel scenario.
306 static int __cifs_reconnect(struct TCP_Server_Info *server,
307 bool mark_smb_session)
311 if (!cifs_tcp_ses_needs_reconnect(server, 1))
314 cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
318 mutex_lock(&server->srv_mutex);
320 if (!cifs_swn_set_server_dstaddr(server)) {
321 /* resolve the hostname again to make sure that IP address is up-to-date */
322 rc = reconn_set_ipaddr_from_hostname(server);
323 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
326 if (cifs_rdma_enabled(server))
327 rc = smbd_reconnect(server);
329 rc = generic_ip_connect(server);
331 mutex_unlock(&server->srv_mutex);
332 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
335 atomic_inc(&tcpSesReconnectCount);
336 set_credits(server, 1);
337 spin_lock(&cifs_tcp_ses_lock);
338 if (server->tcpStatus != CifsExiting)
339 server->tcpStatus = CifsNeedNegotiate;
340 spin_unlock(&cifs_tcp_ses_lock);
341 cifs_swn_reset_server_dstaddr(server);
342 mutex_unlock(&server->srv_mutex);
344 } while (server->tcpStatus == CifsNeedReconnect);
346 if (server->tcpStatus == CifsNeedNegotiate)
347 mod_delayed_work(cifsiod_wq, &server->echo, 0);
349 wake_up(&server->response_q);
353 #ifdef CONFIG_CIFS_DFS_UPCALL
354 static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
359 if (!cifs_swn_set_server_dstaddr(server)) {
360 if (server->hostname != target) {
361 hostname = extract_hostname(target);
362 if (!IS_ERR(hostname)) {
363 kfree(server->hostname);
364 server->hostname = hostname;
366 cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
367 __func__, PTR_ERR(hostname));
368 cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
372 /* resolve the hostname again to make sure that IP address is up-to-date. */
373 rc = reconn_set_ipaddr_from_hostname(server);
374 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
376 /* Reconnect the socket */
377 if (cifs_rdma_enabled(server))
378 rc = smbd_reconnect(server);
380 rc = generic_ip_connect(server);
385 static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
386 struct dfs_cache_tgt_iterator **target_hint)
389 struct dfs_cache_tgt_iterator *tit;
393 /* If dfs target list is empty, then reconnect to last server */
394 tit = dfs_cache_get_tgt_iterator(tl);
396 return __reconnect_target_unlocked(server, server->hostname);
398 /* Otherwise, try every dfs target in @tl */
399 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
400 rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
410 reconnect_dfs_server(struct TCP_Server_Info *server,
411 bool mark_smb_session)
414 const char *refpath = server->current_fullpath + 1;
415 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
416 struct dfs_cache_tgt_iterator *target_hint = NULL;
420 * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
422 * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
423 * targets (server->nr_targets). It's also possible that the cached referral was cleared
424 * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
425 * refreshing the referral, so, in this case, default it to 1.
427 if (!dfs_cache_noreq_find(refpath, NULL, &tl))
428 num_targets = dfs_cache_get_nr_tgts(&tl);
432 if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
435 cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
439 mutex_lock(&server->srv_mutex);
441 rc = reconnect_target_unlocked(server, &tl, &target_hint);
443 /* Failed to reconnect socket */
444 mutex_unlock(&server->srv_mutex);
445 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
450 * Socket was created. Update tcp session status to CifsNeedNegotiate so that a
451 * process waiting for reconnect will know it needs to re-establish session and tcon
452 * through the reconnected target server.
454 atomic_inc(&tcpSesReconnectCount);
455 set_credits(server, 1);
456 spin_lock(&cifs_tcp_ses_lock);
457 if (server->tcpStatus != CifsExiting)
458 server->tcpStatus = CifsNeedNegotiate;
459 spin_unlock(&cifs_tcp_ses_lock);
460 cifs_swn_reset_server_dstaddr(server);
461 mutex_unlock(&server->srv_mutex);
462 } while (server->tcpStatus == CifsNeedReconnect);
465 dfs_cache_noreq_update_tgthint(refpath, target_hint);
467 dfs_cache_free_tgts(&tl);
469 /* Need to set up echo worker again once connection has been established */
470 if (server->tcpStatus == CifsNeedNegotiate)
471 mod_delayed_work(cifsiod_wq, &server->echo, 0);
473 wake_up(&server->response_q);
477 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
479 /* If tcp session is not an dfs connection, then reconnect to last target server */
480 spin_lock(&cifs_tcp_ses_lock);
481 if (!server->is_dfs_conn || !server->origin_fullpath || !server->leaf_fullpath) {
482 spin_unlock(&cifs_tcp_ses_lock);
483 return __cifs_reconnect(server, mark_smb_session);
485 spin_unlock(&cifs_tcp_ses_lock);
487 return reconnect_dfs_server(server, mark_smb_session);
490 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
492 return __cifs_reconnect(server, mark_smb_session);
497 cifs_echo_request(struct work_struct *work)
500 struct TCP_Server_Info *server = container_of(work,
501 struct TCP_Server_Info, echo.work);
504 * We cannot send an echo if it is disabled.
505 * Also, no need to ping if we got a response recently.
508 if (server->tcpStatus == CifsNeedReconnect ||
509 server->tcpStatus == CifsExiting ||
510 server->tcpStatus == CifsNew ||
511 (server->ops->can_echo && !server->ops->can_echo(server)) ||
512 time_before(jiffies, server->lstrp + server->echo_interval - HZ))
515 rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
517 cifs_dbg(FYI, "Unable to send echo request to server: %s\n",
520 /* Check witness registrations */
524 queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
528 allocate_buffers(struct TCP_Server_Info *server)
530 if (!server->bigbuf) {
531 server->bigbuf = (char *)cifs_buf_get();
532 if (!server->bigbuf) {
533 cifs_server_dbg(VFS, "No memory for large SMB response\n");
535 /* retry will check if exiting */
538 } else if (server->large_buf) {
539 /* we are reusing a dirty large buf, clear its start */
540 memset(server->bigbuf, 0, HEADER_SIZE(server));
543 if (!server->smallbuf) {
544 server->smallbuf = (char *)cifs_small_buf_get();
545 if (!server->smallbuf) {
546 cifs_server_dbg(VFS, "No memory for SMB response\n");
548 /* retry will check if exiting */
551 /* beginning of smb buffer is cleared in our buf_get */
553 /* if existing small buf clear beginning */
554 memset(server->smallbuf, 0, HEADER_SIZE(server));
561 server_unresponsive(struct TCP_Server_Info *server)
564 * We need to wait 3 echo intervals to make sure we handle such
566 * 1s client sends a normal SMB request
567 * 2s client gets a response
568 * 30s echo workqueue job pops, and decides we got a response recently
569 * and don't need to send another
571 * 65s kernel_recvmsg times out, and we see that we haven't gotten
572 * a response in >60s.
574 if ((server->tcpStatus == CifsGood ||
575 server->tcpStatus == CifsNeedNegotiate) &&
576 (!server->ops->can_echo || server->ops->can_echo(server)) &&
577 time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
578 cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
579 (3 * server->echo_interval) / HZ);
580 cifs_reconnect(server, false);
588 zero_credits(struct TCP_Server_Info *server)
592 spin_lock(&server->req_lock);
593 val = server->credits + server->echo_credits + server->oplock_credits;
594 if (server->in_flight == 0 && val == 0) {
595 spin_unlock(&server->req_lock);
598 spin_unlock(&server->req_lock);
603 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
608 smb_msg->msg_control = NULL;
609 smb_msg->msg_controllen = 0;
611 for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
614 /* reconnect if no credits and no requests in flight */
615 if (zero_credits(server)) {
616 cifs_reconnect(server, false);
617 return -ECONNABORTED;
620 if (server_unresponsive(server))
621 return -ECONNABORTED;
622 if (cifs_rdma_enabled(server) && server->smbd_conn)
623 length = smbd_recv(server->smbd_conn, smb_msg);
625 length = sock_recvmsg(server->ssocket, smb_msg, 0);
627 if (server->tcpStatus == CifsExiting)
630 if (server->tcpStatus == CifsNeedReconnect) {
631 cifs_reconnect(server, false);
632 return -ECONNABORTED;
635 if (length == -ERESTARTSYS ||
639 * Minimum sleep to prevent looping, allowing socket
640 * to clear and app threads to set tcpStatus
641 * CifsNeedReconnect if server hung.
643 usleep_range(1000, 2000);
649 cifs_dbg(FYI, "Received no data or error: %d\n", length);
650 cifs_reconnect(server, false);
651 return -ECONNABORTED;
658 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
659 unsigned int to_read)
661 struct msghdr smb_msg;
662 struct kvec iov = {.iov_base = buf, .iov_len = to_read};
663 iov_iter_kvec(&smb_msg.msg_iter, READ, &iov, 1, to_read);
665 return cifs_readv_from_socket(server, &smb_msg);
669 cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
671 struct msghdr smb_msg;
674 * iov_iter_discard already sets smb_msg.type and count and iov_offset
675 * and cifs_readv_from_socket sets msg_control and msg_controllen
676 * so little to initialize in struct msghdr
678 smb_msg.msg_name = NULL;
679 smb_msg.msg_namelen = 0;
680 iov_iter_discard(&smb_msg.msg_iter, READ, to_read);
682 return cifs_readv_from_socket(server, &smb_msg);
686 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
687 unsigned int page_offset, unsigned int to_read)
689 struct msghdr smb_msg;
690 struct bio_vec bv = {
691 .bv_page = page, .bv_len = to_read, .bv_offset = page_offset};
692 iov_iter_bvec(&smb_msg.msg_iter, READ, &bv, 1, to_read);
693 return cifs_readv_from_socket(server, &smb_msg);
697 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
700 * The first byte big endian of the length field,
701 * is actually not part of the length but the type
702 * with the most common, zero, as regular data.
705 case RFC1002_SESSION_MESSAGE:
706 /* Regular SMB response */
708 case RFC1002_SESSION_KEEP_ALIVE:
709 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
711 case RFC1002_POSITIVE_SESSION_RESPONSE:
712 cifs_dbg(FYI, "RFC 1002 positive session response\n");
714 case RFC1002_NEGATIVE_SESSION_RESPONSE:
716 * We get this from Windows 98 instead of an error on
717 * SMB negprot response.
719 cifs_dbg(FYI, "RFC 1002 negative session response\n");
720 /* give server a second to clean up */
723 * Always try 445 first on reconnect since we get NACK
724 * on some if we ever connected to port 139 (the NACK
725 * is since we do not begin with RFC1001 session
728 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
729 cifs_reconnect(server, true);
732 cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
733 cifs_reconnect(server, true);
740 dequeue_mid(struct mid_q_entry *mid, bool malformed)
742 #ifdef CONFIG_CIFS_STATS2
743 mid->when_received = jiffies;
745 spin_lock(&GlobalMid_Lock);
747 mid->mid_state = MID_RESPONSE_RECEIVED;
749 mid->mid_state = MID_RESPONSE_MALFORMED;
751 * Trying to handle/dequeue a mid after the send_recv()
752 * function has finished processing it is a bug.
754 if (mid->mid_flags & MID_DELETED) {
755 spin_unlock(&GlobalMid_Lock);
756 pr_warn_once("trying to dequeue a deleted mid\n");
758 list_del_init(&mid->qhead);
759 mid->mid_flags |= MID_DELETED;
760 spin_unlock(&GlobalMid_Lock);
765 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
767 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
770 * SMB1 does not use credits.
772 if (server->vals->header_preamble_size)
775 return le16_to_cpu(shdr->CreditRequest);
779 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
780 char *buf, int malformed)
782 if (server->ops->check_trans2 &&
783 server->ops->check_trans2(mid, server, buf, malformed))
785 mid->credits_received = smb2_get_credits_from_hdr(buf, server);
787 mid->large_buf = server->large_buf;
788 /* Was previous buf put in mpx struct for multi-rsp? */
789 if (!mid->multiRsp) {
790 /* smb buffer will be freed by user thread */
791 if (server->large_buf)
792 server->bigbuf = NULL;
794 server->smallbuf = NULL;
796 dequeue_mid(mid, malformed);
799 static void clean_demultiplex_info(struct TCP_Server_Info *server)
803 /* take it off the list, if it's not already */
804 spin_lock(&cifs_tcp_ses_lock);
805 list_del_init(&server->tcp_ses_list);
806 spin_unlock(&cifs_tcp_ses_lock);
808 cancel_delayed_work_sync(&server->echo);
809 cancel_delayed_work_sync(&server->resolve);
811 spin_lock(&GlobalMid_Lock);
812 server->tcpStatus = CifsExiting;
813 spin_unlock(&GlobalMid_Lock);
814 wake_up_all(&server->response_q);
816 /* check if we have blocked requests that need to free */
817 spin_lock(&server->req_lock);
818 if (server->credits <= 0)
820 spin_unlock(&server->req_lock);
822 * Although there should not be any requests blocked on this queue it
823 * can not hurt to be paranoid and try to wake up requests that may
824 * haven been blocked when more than 50 at time were on the wire to the
825 * same server - they now will see the session is in exit state and get
826 * out of SendReceive.
828 wake_up_all(&server->request_q);
829 /* give those requests time to exit */
831 if (cifs_rdma_enabled(server))
832 smbd_destroy(server);
833 if (server->ssocket) {
834 sock_release(server->ssocket);
835 server->ssocket = NULL;
838 if (!list_empty(&server->pending_mid_q)) {
839 struct list_head dispose_list;
840 struct mid_q_entry *mid_entry;
841 struct list_head *tmp, *tmp2;
843 INIT_LIST_HEAD(&dispose_list);
844 spin_lock(&GlobalMid_Lock);
845 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
846 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
847 cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
848 kref_get(&mid_entry->refcount);
849 mid_entry->mid_state = MID_SHUTDOWN;
850 list_move(&mid_entry->qhead, &dispose_list);
851 mid_entry->mid_flags |= MID_DELETED;
853 spin_unlock(&GlobalMid_Lock);
855 /* now walk dispose list and issue callbacks */
856 list_for_each_safe(tmp, tmp2, &dispose_list) {
857 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
858 cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
859 list_del_init(&mid_entry->qhead);
860 mid_entry->callback(mid_entry);
861 cifs_mid_q_entry_release(mid_entry);
863 /* 1/8th of sec is more than enough time for them to exit */
867 if (!list_empty(&server->pending_mid_q)) {
869 * mpx threads have not exited yet give them at least the smb
870 * send timeout time for long ops.
872 * Due to delays on oplock break requests, we need to wait at
873 * least 45 seconds before giving up on a request getting a
874 * response and going ahead and killing cifsd.
876 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
879 * If threads still have not exited they are probably never
880 * coming home not much else we can do but free the memory.
884 #ifdef CONFIG_CIFS_DFS_UPCALL
885 kfree(server->origin_fullpath);
886 kfree(server->leaf_fullpath);
890 length = atomic_dec_return(&tcpSesAllocCount);
892 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
896 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
899 char *buf = server->smallbuf;
900 unsigned int pdu_length = server->pdu_size;
902 /* make sure this will fit in a large buffer */
903 if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
904 server->vals->header_preamble_size) {
905 cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
906 cifs_reconnect(server, true);
907 return -ECONNABORTED;
910 /* switch to large buffer if too big for a small one */
911 if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
912 server->large_buf = true;
913 memcpy(server->bigbuf, buf, server->total_read);
914 buf = server->bigbuf;
917 /* now read the rest */
918 length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
919 pdu_length - HEADER_SIZE(server) + 1
920 + server->vals->header_preamble_size);
924 server->total_read += length;
926 dump_smb(buf, server->total_read);
928 return cifs_handle_standard(server, mid);
932 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
934 char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
938 * We know that we received enough to get to the MID as we
939 * checked the pdu_length earlier. Now check to see
940 * if the rest of the header is OK. We borrow the length
941 * var for the rest of the loop to avoid a new stack var.
943 * 48 bytes is enough to display the header and a little bit
944 * into the payload for debugging purposes.
946 length = server->ops->check_message(buf, server->total_read, server);
948 cifs_dump_mem("Bad SMB: ", buf,
949 min_t(unsigned int, server->total_read, 48));
951 if (server->ops->is_session_expired &&
952 server->ops->is_session_expired(buf)) {
953 cifs_reconnect(server, true);
957 if (server->ops->is_status_pending &&
958 server->ops->is_status_pending(buf, server))
964 handle_mid(mid, server, buf, length);
969 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
971 struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
972 int scredits, in_flight;
975 * SMB1 does not use credits.
977 if (server->vals->header_preamble_size)
980 if (shdr->CreditRequest) {
981 spin_lock(&server->req_lock);
982 server->credits += le16_to_cpu(shdr->CreditRequest);
983 scredits = server->credits;
984 in_flight = server->in_flight;
985 spin_unlock(&server->req_lock);
986 wake_up(&server->request_q);
988 trace_smb3_add_credits(server->CurrentMid,
989 server->conn_id, server->hostname, scredits,
990 le16_to_cpu(shdr->CreditRequest), in_flight);
991 cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
992 __func__, le16_to_cpu(shdr->CreditRequest),
999 cifs_demultiplex_thread(void *p)
1001 int i, num_mids, length;
1002 struct TCP_Server_Info *server = p;
1003 unsigned int pdu_length;
1004 unsigned int next_offset;
1006 struct task_struct *task_to_wake = NULL;
1007 struct mid_q_entry *mids[MAX_COMPOUND];
1008 char *bufs[MAX_COMPOUND];
1009 unsigned int noreclaim_flag, num_io_timeout = 0;
1011 noreclaim_flag = memalloc_noreclaim_save();
1012 cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1014 length = atomic_inc_return(&tcpSesAllocCount);
1016 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1019 allow_kernel_signal(SIGKILL);
1020 while (server->tcpStatus != CifsExiting) {
1021 if (try_to_freeze())
1024 if (!allocate_buffers(server))
1027 server->large_buf = false;
1028 buf = server->smallbuf;
1029 pdu_length = 4; /* enough to get RFC1001 header */
1031 length = cifs_read_from_socket(server, buf, pdu_length);
1035 if (server->vals->header_preamble_size == 0)
1036 server->total_read = 0;
1038 server->total_read = length;
1041 * The right amount was read from socket - 4 bytes,
1042 * so we can now interpret the length field.
1044 pdu_length = get_rfc1002_length(buf);
1046 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1047 if (!is_smb_response(server, buf[0]))
1050 server->pdu_size = pdu_length;
1052 /* make sure we have enough to get to the MID */
1053 if (server->pdu_size < HEADER_SIZE(server) - 1 -
1054 server->vals->header_preamble_size) {
1055 cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1057 cifs_reconnect(server, true);
1061 /* read down to the MID */
1062 length = cifs_read_from_socket(server,
1063 buf + server->vals->header_preamble_size,
1064 HEADER_SIZE(server) - 1
1065 - server->vals->header_preamble_size);
1068 server->total_read += length;
1070 if (server->ops->next_header) {
1071 next_offset = server->ops->next_header(buf);
1073 server->pdu_size = next_offset;
1076 memset(mids, 0, sizeof(mids));
1077 memset(bufs, 0, sizeof(bufs));
1080 if (server->ops->is_transform_hdr &&
1081 server->ops->receive_transform &&
1082 server->ops->is_transform_hdr(buf)) {
1083 length = server->ops->receive_transform(server,
1088 mids[0] = server->ops->find_mid(server, buf);
1092 if (!mids[0] || !mids[0]->receive)
1093 length = standard_receive3(server, mids[0]);
1095 length = mids[0]->receive(server, mids[0]);
1099 for (i = 0; i < num_mids; i++)
1101 cifs_mid_q_entry_release(mids[i]);
1105 if (server->ops->is_status_io_timeout &&
1106 server->ops->is_status_io_timeout(buf)) {
1108 if (num_io_timeout > NUM_STATUS_IO_TIMEOUT) {
1109 cifs_reconnect(server, false);
1115 server->lstrp = jiffies;
1117 for (i = 0; i < num_mids; i++) {
1118 if (mids[i] != NULL) {
1119 mids[i]->resp_buf_size = server->pdu_size;
1121 if (bufs[i] && server->ops->is_network_name_deleted)
1122 server->ops->is_network_name_deleted(bufs[i],
1125 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1126 mids[i]->callback(mids[i]);
1128 cifs_mid_q_entry_release(mids[i]);
1129 } else if (server->ops->is_oplock_break &&
1130 server->ops->is_oplock_break(bufs[i],
1132 smb2_add_credits_from_hdr(bufs[i], server);
1133 cifs_dbg(FYI, "Received oplock break\n");
1135 cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1136 atomic_read(&midCount));
1137 cifs_dump_mem("Received Data is: ", bufs[i],
1138 HEADER_SIZE(server));
1139 smb2_add_credits_from_hdr(bufs[i], server);
1140 #ifdef CONFIG_CIFS_DEBUG2
1141 if (server->ops->dump_detail)
1142 server->ops->dump_detail(bufs[i],
1144 cifs_dump_mids(server);
1145 #endif /* CIFS_DEBUG2 */
1149 if (pdu_length > server->pdu_size) {
1150 if (!allocate_buffers(server))
1152 pdu_length -= server->pdu_size;
1153 server->total_read = 0;
1154 server->large_buf = false;
1155 buf = server->smallbuf;
1158 } /* end while !EXITING */
1160 /* buffer usually freed in free_mid - need to free it here on exit */
1161 cifs_buf_release(server->bigbuf);
1162 if (server->smallbuf) /* no sense logging a debug message if NULL */
1163 cifs_small_buf_release(server->smallbuf);
1165 task_to_wake = xchg(&server->tsk, NULL);
1166 clean_demultiplex_info(server);
1168 /* if server->tsk was NULL then wait for a signal before exiting */
1169 if (!task_to_wake) {
1170 set_current_state(TASK_INTERRUPTIBLE);
1171 while (!signal_pending(current)) {
1173 set_current_state(TASK_INTERRUPTIBLE);
1175 set_current_state(TASK_RUNNING);
1178 memalloc_noreclaim_restore(noreclaim_flag);
1179 module_put_and_exit(0);
1183 * Returns true if srcaddr isn't specified and rhs isn't specified, or
1184 * if srcaddr is specified and matches the IP address of the rhs argument
1187 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1189 switch (srcaddr->sa_family) {
1191 return (rhs->sa_family == AF_UNSPEC);
1193 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1194 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1195 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1198 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1199 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1200 return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
1204 return false; /* don't expect to be here */
1209 * If no port is specified in addr structure, we try to match with 445 port
1210 * and if it fails - with 139 ports. It should be called only if address
1211 * families of server and addr are equal.
1214 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1216 __be16 port, *sport;
1218 /* SMBDirect manages its own ports, don't match it here */
1222 switch (addr->sa_family) {
1224 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1225 port = ((struct sockaddr_in *) addr)->sin_port;
1228 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1229 port = ((struct sockaddr_in6 *) addr)->sin6_port;
1237 port = htons(CIFS_PORT);
1241 port = htons(RFC1001_PORT);
1244 return port == *sport;
1248 match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
1249 struct sockaddr *srcaddr)
1251 switch (addr->sa_family) {
1253 struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
1254 struct sockaddr_in *srv_addr4 =
1255 (struct sockaddr_in *)&server->dstaddr;
1257 if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
1262 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
1263 struct sockaddr_in6 *srv_addr6 =
1264 (struct sockaddr_in6 *)&server->dstaddr;
1266 if (!ipv6_addr_equal(&addr6->sin6_addr,
1267 &srv_addr6->sin6_addr))
1269 if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
1275 return false; /* don't expect to be here */
1278 if (!cifs_match_ipaddr(srcaddr, (struct sockaddr *)&server->srcaddr))
1285 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1288 * The select_sectype function should either return the ctx->sectype
1289 * that was specified, or "Unspecified" if that sectype was not
1290 * compatible with the given NEGOTIATE request.
1292 if (server->ops->select_sectype(server, ctx->sectype)
1297 * Now check if signing mode is acceptable. No need to check
1298 * global_secflags at this point since if MUST_SIGN is set then
1299 * the server->sign had better be too.
1301 if (ctx->sign && !server->sign)
1307 static int match_server(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1309 struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1311 if (ctx->nosharesock)
1314 /* this server does not share socket */
1315 if (server->nosharesock)
1318 /* If multidialect negotiation see if existing sessions match one */
1319 if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1320 if (server->vals->protocol_id < SMB30_PROT_ID)
1322 } else if (strcmp(ctx->vals->version_string,
1323 SMBDEFAULT_VERSION_STRING) == 0) {
1324 if (server->vals->protocol_id < SMB21_PROT_ID)
1326 } else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1329 if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1332 if (strcasecmp(server->hostname, ctx->server_hostname))
1335 if (!match_address(server, addr,
1336 (struct sockaddr *)&ctx->srcaddr))
1339 if (!match_port(server, addr))
1342 if (!match_security(server, ctx))
1345 if (server->echo_interval != ctx->echo_interval * HZ)
1348 if (server->rdma != ctx->rdma)
1351 if (server->ignore_signature != ctx->ignore_signature)
1354 if (server->min_offload != ctx->min_offload)
1360 struct TCP_Server_Info *
1361 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1363 struct TCP_Server_Info *server;
1365 spin_lock(&cifs_tcp_ses_lock);
1366 list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1367 #ifdef CONFIG_CIFS_DFS_UPCALL
1369 * DFS failover implementation in cifs_reconnect() requires unique tcp sessions for
1370 * DFS connections to do failover properly, so avoid sharing them with regular
1371 * shares or even links that may connect to same server but having completely
1372 * different failover targets.
1374 if (server->is_dfs_conn)
1378 * Skip ses channels since they're only handled in lower layers
1379 * (e.g. cifs_send_recv).
1381 if (CIFS_SERVER_IS_CHAN(server) || !match_server(server, ctx))
1384 ++server->srv_count;
1385 spin_unlock(&cifs_tcp_ses_lock);
1386 cifs_dbg(FYI, "Existing tcp session with server found\n");
1389 spin_unlock(&cifs_tcp_ses_lock);
1394 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1396 struct task_struct *task;
1398 spin_lock(&cifs_tcp_ses_lock);
1399 if (--server->srv_count > 0) {
1400 spin_unlock(&cifs_tcp_ses_lock);
1404 /* srv_count can never go negative */
1405 WARN_ON(server->srv_count < 0);
1407 put_net(cifs_net_ns(server));
1409 list_del_init(&server->tcp_ses_list);
1410 spin_unlock(&cifs_tcp_ses_lock);
1412 /* For secondary channels, we pick up ref-count on the primary server */
1413 if (CIFS_SERVER_IS_CHAN(server))
1414 cifs_put_tcp_session(server->primary_server, from_reconnect);
1416 cancel_delayed_work_sync(&server->echo);
1417 cancel_delayed_work_sync(&server->resolve);
1421 * Avoid deadlock here: reconnect work calls
1422 * cifs_put_tcp_session() at its end. Need to be sure
1423 * that reconnect work does nothing with server pointer after
1426 cancel_delayed_work(&server->reconnect);
1428 cancel_delayed_work_sync(&server->reconnect);
1430 spin_lock(&GlobalMid_Lock);
1431 server->tcpStatus = CifsExiting;
1432 spin_unlock(&GlobalMid_Lock);
1434 cifs_crypto_secmech_release(server);
1436 /* fscache server cookies are based on primary channel only */
1437 if (!CIFS_SERVER_IS_CHAN(server))
1438 cifs_fscache_release_client_cookie(server);
1440 kfree(server->session_key.response);
1441 server->session_key.response = NULL;
1442 server->session_key.len = 0;
1443 kfree(server->hostname);
1445 task = xchg(&server->tsk, NULL);
1447 send_sig(SIGKILL, task, 1);
1450 struct TCP_Server_Info *
1451 cifs_get_tcp_session(struct smb3_fs_context *ctx,
1452 struct TCP_Server_Info *primary_server)
1454 struct TCP_Server_Info *tcp_ses = NULL;
1457 cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1459 /* see if we already have a matching tcp_ses */
1460 tcp_ses = cifs_find_tcp_session(ctx);
1464 tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1470 tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1471 if (!tcp_ses->hostname) {
1476 if (ctx->nosharesock)
1477 tcp_ses->nosharesock = true;
1479 tcp_ses->ops = ctx->ops;
1480 tcp_ses->vals = ctx->vals;
1481 cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1483 tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1484 tcp_ses->noblockcnt = ctx->rootfs;
1485 tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1486 tcp_ses->noautotune = ctx->noautotune;
1487 tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1488 tcp_ses->rdma = ctx->rdma;
1489 tcp_ses->in_flight = 0;
1490 tcp_ses->max_in_flight = 0;
1491 tcp_ses->credits = 1;
1492 if (primary_server) {
1493 spin_lock(&cifs_tcp_ses_lock);
1494 ++primary_server->srv_count;
1495 tcp_ses->primary_server = primary_server;
1496 spin_unlock(&cifs_tcp_ses_lock);
1498 init_waitqueue_head(&tcp_ses->response_q);
1499 init_waitqueue_head(&tcp_ses->request_q);
1500 INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1501 mutex_init(&tcp_ses->srv_mutex);
1502 memcpy(tcp_ses->workstation_RFC1001_name,
1503 ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1504 memcpy(tcp_ses->server_RFC1001_name,
1505 ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1506 tcp_ses->session_estab = false;
1507 tcp_ses->sequence_number = 0;
1508 tcp_ses->reconnect_instance = 1;
1509 tcp_ses->lstrp = jiffies;
1510 tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1511 spin_lock_init(&tcp_ses->req_lock);
1512 INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1513 INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1514 INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1515 INIT_DELAYED_WORK(&tcp_ses->resolve, cifs_resolve_server);
1516 INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1517 mutex_init(&tcp_ses->reconnect_mutex);
1518 #ifdef CONFIG_CIFS_DFS_UPCALL
1519 mutex_init(&tcp_ses->refpath_lock);
1521 memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1522 sizeof(tcp_ses->srcaddr));
1523 memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1524 sizeof(tcp_ses->dstaddr));
1525 if (ctx->use_client_guid)
1526 memcpy(tcp_ses->client_guid, ctx->client_guid,
1527 SMB2_CLIENT_GUID_SIZE);
1529 generate_random_uuid(tcp_ses->client_guid);
1531 * at this point we are the only ones with the pointer
1532 * to the struct since the kernel thread not created yet
1533 * no need to spinlock this init of tcpStatus or srv_count
1535 tcp_ses->tcpStatus = CifsNew;
1536 ++tcp_ses->srv_count;
1538 if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1539 ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1540 tcp_ses->echo_interval = ctx->echo_interval * HZ;
1542 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1543 if (tcp_ses->rdma) {
1544 #ifndef CONFIG_CIFS_SMB_DIRECT
1545 cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1547 goto out_err_crypto_release;
1549 tcp_ses->smbd_conn = smbd_get_connection(
1550 tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1551 if (tcp_ses->smbd_conn) {
1552 cifs_dbg(VFS, "RDMA transport established\n");
1554 goto smbd_connected;
1557 goto out_err_crypto_release;
1560 rc = ip_connect(tcp_ses);
1562 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1563 goto out_err_crypto_release;
1567 * since we're in a cifs function already, we know that
1568 * this will succeed. No need for try_module_get().
1570 __module_get(THIS_MODULE);
1571 tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1573 if (IS_ERR(tcp_ses->tsk)) {
1574 rc = PTR_ERR(tcp_ses->tsk);
1575 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1576 module_put(THIS_MODULE);
1577 goto out_err_crypto_release;
1579 tcp_ses->min_offload = ctx->min_offload;
1581 * at this point we are the only ones with the pointer
1582 * to the struct since the kernel thread not created yet
1583 * no need to spinlock this update of tcpStatus
1585 tcp_ses->tcpStatus = CifsNeedNegotiate;
1587 if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1588 tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1590 tcp_ses->max_credits = ctx->max_credits;
1592 tcp_ses->nr_targets = 1;
1593 tcp_ses->ignore_signature = ctx->ignore_signature;
1594 /* thread spawned, put it on the list */
1595 spin_lock(&cifs_tcp_ses_lock);
1596 list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1597 spin_unlock(&cifs_tcp_ses_lock);
1599 /* fscache server cookies are based on primary channel only */
1600 if (!CIFS_SERVER_IS_CHAN(tcp_ses))
1601 cifs_fscache_get_client_cookie(tcp_ses);
1602 #ifdef CONFIG_CIFS_FSCACHE
1604 tcp_ses->fscache = tcp_ses->primary_server->fscache;
1605 #endif /* CONFIG_CIFS_FSCACHE */
1607 /* queue echo request delayed work */
1608 queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1610 /* queue dns resolution delayed work */
1611 cifs_dbg(FYI, "%s: next dns resolution scheduled for %d seconds in the future\n",
1612 __func__, SMB_DNS_RESOLVE_INTERVAL_DEFAULT);
1614 queue_delayed_work(cifsiod_wq, &tcp_ses->resolve, (SMB_DNS_RESOLVE_INTERVAL_DEFAULT * HZ));
1618 out_err_crypto_release:
1619 cifs_crypto_secmech_release(tcp_ses);
1621 put_net(cifs_net_ns(tcp_ses));
1625 if (CIFS_SERVER_IS_CHAN(tcp_ses))
1626 cifs_put_tcp_session(tcp_ses->primary_server, false);
1627 kfree(tcp_ses->hostname);
1628 if (tcp_ses->ssocket)
1629 sock_release(tcp_ses->ssocket);
1635 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1637 if (ctx->sectype != Unspecified &&
1638 ctx->sectype != ses->sectype)
1642 * If an existing session is limited to less channels than
1643 * requested, it should not be reused
1645 spin_lock(&ses->chan_lock);
1646 if (ses->chan_max < ctx->max_channels) {
1647 spin_unlock(&ses->chan_lock);
1650 spin_unlock(&ses->chan_lock);
1652 switch (ses->sectype) {
1654 if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1658 /* NULL username means anonymous session */
1659 if (ses->user_name == NULL) {
1665 /* anything else takes username/password */
1666 if (strncmp(ses->user_name,
1667 ctx->username ? ctx->username : "",
1668 CIFS_MAX_USERNAME_LEN))
1670 if ((ctx->username && strlen(ctx->username) != 0) &&
1671 ses->password != NULL &&
1672 strncmp(ses->password,
1673 ctx->password ? ctx->password : "",
1674 CIFS_MAX_PASSWORD_LEN))
1681 * cifs_setup_ipc - helper to setup the IPC tcon for the session
1682 * @ses: smb session to issue the request on
1683 * @ctx: the superblock configuration context to use for building the
1684 * new tree connection for the IPC (interprocess communication RPC)
1686 * A new IPC connection is made and stored in the session
1687 * tcon_ipc. The IPC tcon has the same lifetime as the session.
1690 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1693 struct cifs_tcon *tcon;
1694 char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1696 struct TCP_Server_Info *server = ses->server;
1699 * If the mount request that resulted in the creation of the
1700 * session requires encryption, force IPC to be encrypted too.
1703 if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1706 cifs_server_dbg(VFS,
1707 "IPC: server doesn't support encryption\n");
1712 tcon = tconInfoAlloc();
1716 scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1722 rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1726 cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1731 cifs_dbg(FYI, "IPC tcon rc = %d ipc tid = %d\n", rc, tcon->tid);
1733 ses->tcon_ipc = tcon;
1739 * cifs_free_ipc - helper to release the session IPC tcon
1740 * @ses: smb session to unmount the IPC from
1742 * Needs to be called everytime a session is destroyed.
1744 * On session close, the IPC is closed and the server must release all tcons of the session.
1745 * No need to send a tree disconnect here.
1747 * Besides, it will make the server to not close durable and resilient files on session close, as
1748 * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1751 cifs_free_ipc(struct cifs_ses *ses)
1753 struct cifs_tcon *tcon = ses->tcon_ipc;
1759 ses->tcon_ipc = NULL;
1763 static struct cifs_ses *
1764 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1766 struct cifs_ses *ses;
1768 spin_lock(&cifs_tcp_ses_lock);
1769 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1770 if (ses->status == CifsExiting)
1772 if (!match_session(ses, ctx))
1775 spin_unlock(&cifs_tcp_ses_lock);
1778 spin_unlock(&cifs_tcp_ses_lock);
1782 void cifs_put_smb_ses(struct cifs_ses *ses)
1784 unsigned int rc, xid;
1785 unsigned int chan_count;
1786 struct TCP_Server_Info *server = ses->server;
1787 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1789 spin_lock(&cifs_tcp_ses_lock);
1790 if (ses->status == CifsExiting) {
1791 spin_unlock(&cifs_tcp_ses_lock);
1795 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1796 cifs_dbg(FYI, "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->treeName : "NONE");
1798 if (--ses->ses_count > 0) {
1799 spin_unlock(&cifs_tcp_ses_lock);
1802 spin_unlock(&cifs_tcp_ses_lock);
1804 /* ses_count can never go negative */
1805 WARN_ON(ses->ses_count < 0);
1807 spin_lock(&GlobalMid_Lock);
1808 if (ses->status == CifsGood)
1809 ses->status = CifsExiting;
1810 spin_unlock(&GlobalMid_Lock);
1814 if (ses->status == CifsExiting && server->ops->logoff) {
1816 rc = server->ops->logoff(xid, ses);
1818 cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
1823 spin_lock(&cifs_tcp_ses_lock);
1824 list_del_init(&ses->smb_ses_list);
1825 spin_unlock(&cifs_tcp_ses_lock);
1827 spin_lock(&ses->chan_lock);
1828 chan_count = ses->chan_count;
1829 spin_unlock(&ses->chan_lock);
1831 /* close any extra channels */
1832 if (chan_count > 1) {
1835 for (i = 1; i < chan_count; i++) {
1837 * note: for now, we're okay accessing ses->chans
1838 * without chan_lock. But when chans can go away, we'll
1839 * need to introduce ref counting to make sure that chan
1840 * is not freed from under us.
1842 cifs_put_tcp_session(ses->chans[i].server, 0);
1843 ses->chans[i].server = NULL;
1848 cifs_put_tcp_session(server, 0);
1853 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
1854 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
1856 /* Populate username and pw fields from keyring if possible */
1858 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
1862 const char *delim, *payload;
1866 struct TCP_Server_Info *server = ses->server;
1867 struct sockaddr_in *sa;
1868 struct sockaddr_in6 *sa6;
1869 const struct user_key_payload *upayload;
1871 desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
1875 /* try to find an address key first */
1876 switch (server->dstaddr.ss_family) {
1878 sa = (struct sockaddr_in *)&server->dstaddr;
1879 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
1882 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
1883 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
1886 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
1887 server->dstaddr.ss_family);
1892 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
1893 key = request_key(&key_type_logon, desc, "");
1895 if (!ses->domainName) {
1896 cifs_dbg(FYI, "domainName is NULL\n");
1901 /* didn't work, try to find a domain key */
1902 sprintf(desc, "cifs:d:%s", ses->domainName);
1903 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
1904 key = request_key(&key_type_logon, desc, "");
1912 down_read(&key->sem);
1913 upayload = user_key_payload_locked(key);
1914 if (IS_ERR_OR_NULL(upayload)) {
1915 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
1919 /* find first : in payload */
1920 payload = upayload->data;
1921 delim = strnchr(payload, upayload->datalen, ':');
1922 cifs_dbg(FYI, "payload=%s\n", payload);
1924 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
1930 len = delim - payload;
1931 if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
1932 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
1938 ctx->username = kstrndup(payload, len, GFP_KERNEL);
1939 if (!ctx->username) {
1940 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
1945 cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
1947 len = key->datalen - (len + 1);
1948 if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
1949 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
1951 kfree(ctx->username);
1952 ctx->username = NULL;
1957 ctx->password = kstrndup(delim, len, GFP_KERNEL);
1958 if (!ctx->password) {
1959 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
1962 kfree(ctx->username);
1963 ctx->username = NULL;
1968 * If we have a domain key then we must set the domainName in the
1971 if (is_domain && ses->domainName) {
1972 ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
1973 if (!ctx->domainname) {
1974 cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
1977 kfree(ctx->username);
1978 ctx->username = NULL;
1979 kfree_sensitive(ctx->password);
1980 ctx->password = NULL;
1990 cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
1993 #else /* ! CONFIG_KEYS */
1995 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
1996 struct cifs_ses *ses __attribute__((unused)))
2000 #endif /* CONFIG_KEYS */
2003 * cifs_get_smb_ses - get a session matching @ctx data from @server
2004 * @server: server to setup the session to
2005 * @ctx: superblock configuration context to use to setup the session
2007 * This function assumes it is being called from cifs_mount() where we
2008 * already got a server reference (server refcount +1). See
2009 * cifs_get_tcon() for refcount explanations.
2012 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2016 struct cifs_ses *ses;
2017 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2018 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2022 ses = cifs_find_smb_ses(server, ctx);
2024 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2027 mutex_lock(&ses->session_mutex);
2028 spin_lock(&ses->chan_lock);
2029 if (cifs_chan_needs_reconnect(ses, server)) {
2030 spin_unlock(&ses->chan_lock);
2031 cifs_dbg(FYI, "Session needs reconnect\n");
2033 rc = cifs_negotiate_protocol(xid, ses, server);
2035 mutex_unlock(&ses->session_mutex);
2036 /* problem -- put our ses reference */
2037 cifs_put_smb_ses(ses);
2042 rc = cifs_setup_session(xid, ses, server,
2045 mutex_unlock(&ses->session_mutex);
2046 /* problem -- put our reference */
2047 cifs_put_smb_ses(ses);
2051 spin_lock(&ses->chan_lock);
2053 spin_unlock(&ses->chan_lock);
2054 mutex_unlock(&ses->session_mutex);
2056 /* existing SMB ses has a server reference already */
2057 cifs_put_tcp_session(server, 0);
2062 cifs_dbg(FYI, "Existing smb sess not found\n");
2063 ses = sesInfoAlloc();
2067 /* new SMB session uses our server ref */
2068 ses->server = server;
2069 if (server->dstaddr.ss_family == AF_INET6)
2070 sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2072 sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2074 if (ctx->username) {
2075 ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2076 if (!ses->user_name)
2080 /* ctx->password freed at unmount */
2081 if (ctx->password) {
2082 ses->password = kstrdup(ctx->password, GFP_KERNEL);
2086 if (ctx->domainname) {
2087 ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2088 if (!ses->domainName)
2091 if (ctx->workstation_name) {
2092 ses->workstation_name = kstrdup(ctx->workstation_name,
2094 if (!ses->workstation_name)
2097 if (ctx->domainauto)
2098 ses->domainAuto = ctx->domainauto;
2099 ses->cred_uid = ctx->cred_uid;
2100 ses->linux_uid = ctx->linux_uid;
2102 ses->sectype = ctx->sectype;
2103 ses->sign = ctx->sign;
2104 mutex_lock(&ses->session_mutex);
2106 /* add server as first channel */
2107 spin_lock(&ses->chan_lock);
2108 ses->chans[0].server = server;
2109 ses->chan_count = 1;
2110 ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2111 ses->chans_need_reconnect = 1;
2112 spin_unlock(&ses->chan_lock);
2114 rc = cifs_negotiate_protocol(xid, ses, server);
2116 rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2118 /* each channel uses a different signing key */
2119 memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2120 sizeof(ses->smb3signingkey));
2122 mutex_unlock(&ses->session_mutex);
2127 * success, put it on the list and add it as first channel
2128 * note: the session becomes active soon after this. So you'll
2129 * need to lock before changing something in the session.
2131 spin_lock(&cifs_tcp_ses_lock);
2132 list_add(&ses->smb_ses_list, &server->smb_ses_list);
2133 spin_unlock(&cifs_tcp_ses_lock);
2137 cifs_setup_ipc(ses, ctx);
2147 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2149 if (tcon->tidStatus == CifsExiting)
2151 if (strncmp(tcon->treeName, ctx->UNC, MAX_TREE_SIZE))
2153 if (tcon->seal != ctx->seal)
2155 if (tcon->snapshot_time != ctx->snapshot_time)
2157 if (tcon->handle_timeout != ctx->handle_timeout)
2159 if (tcon->no_lease != ctx->no_lease)
2161 if (tcon->nodelete != ctx->nodelete)
2166 static struct cifs_tcon *
2167 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2169 struct list_head *tmp;
2170 struct cifs_tcon *tcon;
2172 spin_lock(&cifs_tcp_ses_lock);
2173 list_for_each(tmp, &ses->tcon_list) {
2174 tcon = list_entry(tmp, struct cifs_tcon, tcon_list);
2176 if (!match_tcon(tcon, ctx))
2179 spin_unlock(&cifs_tcp_ses_lock);
2182 spin_unlock(&cifs_tcp_ses_lock);
2187 cifs_put_tcon(struct cifs_tcon *tcon)
2190 struct cifs_ses *ses;
2193 * IPC tcon share the lifetime of their session and are
2194 * destroyed in the session put function
2196 if (tcon == NULL || tcon->ipc)
2200 cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2201 spin_lock(&cifs_tcp_ses_lock);
2202 if (--tcon->tc_count > 0) {
2203 spin_unlock(&cifs_tcp_ses_lock);
2207 /* tc_count can never go negative */
2208 WARN_ON(tcon->tc_count < 0);
2210 list_del_init(&tcon->tcon_list);
2211 spin_unlock(&cifs_tcp_ses_lock);
2213 if (tcon->use_witness) {
2216 rc = cifs_swn_unregister(tcon);
2218 cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2224 if (ses->server->ops->tree_disconnect)
2225 ses->server->ops->tree_disconnect(xid, tcon);
2228 cifs_fscache_release_super_cookie(tcon);
2230 cifs_put_smb_ses(ses);
2234 * cifs_get_tcon - get a tcon matching @ctx data from @ses
2235 * @ses: smb session to issue the request on
2236 * @ctx: the superblock configuration context to use for building the
2238 * - tcon refcount is the number of mount points using the tcon.
2239 * - ses refcount is the number of tcon using the session.
2241 * 1. This function assumes it is being called from cifs_mount() where
2242 * we already got a session reference (ses refcount +1).
2244 * 2. Since we're in the context of adding a mount point, the end
2245 * result should be either:
2247 * a) a new tcon already allocated with refcount=1 (1 mount point) and
2248 * its session refcount incremented (1 new tcon). This +1 was
2249 * already done in (1).
2251 * b) an existing tcon with refcount+1 (add a mount point to it) and
2252 * identical ses refcount (no new tcon). Because of (1) we need to
2253 * decrement the ses refcount.
2255 static struct cifs_tcon *
2256 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2259 struct cifs_tcon *tcon;
2261 tcon = cifs_find_tcon(ses, ctx);
2264 * tcon has refcount already incremented but we need to
2265 * decrement extra ses reference gotten by caller (case b)
2267 cifs_dbg(FYI, "Found match on UNC path\n");
2268 cifs_put_smb_ses(ses);
2272 if (!ses->server->ops->tree_connect) {
2277 tcon = tconInfoAlloc();
2283 if (ctx->snapshot_time) {
2284 if (ses->server->vals->protocol_id == 0) {
2286 "Use SMB2 or later for snapshot mount option\n");
2290 tcon->snapshot_time = ctx->snapshot_time;
2293 if (ctx->handle_timeout) {
2294 if (ses->server->vals->protocol_id == 0) {
2296 "Use SMB2.1 or later for handle timeout option\n");
2300 tcon->handle_timeout = ctx->handle_timeout;
2304 if (ctx->password) {
2305 tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2306 if (!tcon->password) {
2313 if (ses->server->vals->protocol_id == 0) {
2315 "SMB3 or later required for encryption\n");
2318 } else if (tcon->ses->server->capabilities &
2319 SMB2_GLOBAL_CAP_ENCRYPTION)
2322 cifs_dbg(VFS, "Encryption is not supported on share\n");
2328 if (ctx->linux_ext) {
2329 if (ses->server->posix_ext_supported) {
2330 tcon->posix_extensions = true;
2331 pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2333 cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2340 * BB Do we need to wrap session_mutex around this TCon call and Unix
2341 * SetFS as we do on SessSetup and reconnect?
2344 rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2347 cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2351 tcon->use_persistent = false;
2352 /* check if SMB2 or later, CIFS does not support persistent handles */
2353 if (ctx->persistent) {
2354 if (ses->server->vals->protocol_id == 0) {
2356 "SMB3 or later required for persistent handles\n");
2359 } else if (ses->server->capabilities &
2360 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2361 tcon->use_persistent = true;
2362 else /* persistent handles requested but not supported */ {
2364 "Persistent handles not supported on share\n");
2368 } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2369 && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2370 && (ctx->nopersistent == false)) {
2371 cifs_dbg(FYI, "enabling persistent handles\n");
2372 tcon->use_persistent = true;
2373 } else if (ctx->resilient) {
2374 if (ses->server->vals->protocol_id == 0) {
2376 "SMB2.1 or later required for resilient handles\n");
2380 tcon->use_resilient = true;
2383 tcon->use_witness = false;
2384 if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2385 if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2386 if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2388 * Set witness in use flag in first place
2389 * to retry registration in the echo task
2391 tcon->use_witness = true;
2392 /* And try to register immediately */
2393 rc = cifs_swn_register(tcon);
2395 cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2399 /* TODO: try to extend for non-cluster uses (eg multichannel) */
2400 cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2405 cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2411 /* If the user really knows what they are doing they can override */
2412 if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2414 cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2415 else if (ctx->cache_rw)
2416 cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2419 if (ctx->no_lease) {
2420 if (ses->server->vals->protocol_id == 0) {
2422 "SMB2 or later required for nolease option\n");
2426 tcon->no_lease = ctx->no_lease;
2430 * We can have only one retry value for a connection to a share so for
2431 * resources mounted more than once to the same server share the last
2432 * value passed in for the retry flag is used.
2434 tcon->retry = ctx->retry;
2435 tcon->nocase = ctx->nocase;
2436 if (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING)
2437 tcon->nohandlecache = ctx->nohandlecache;
2439 tcon->nohandlecache = true;
2440 tcon->nodelete = ctx->nodelete;
2441 tcon->local_lease = ctx->local_lease;
2442 INIT_LIST_HEAD(&tcon->pending_opens);
2444 spin_lock(&cifs_tcp_ses_lock);
2445 list_add(&tcon->tcon_list, &ses->tcon_list);
2446 spin_unlock(&cifs_tcp_ses_lock);
2456 cifs_put_tlink(struct tcon_link *tlink)
2458 if (!tlink || IS_ERR(tlink))
2461 if (!atomic_dec_and_test(&tlink->tl_count) ||
2462 test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2463 tlink->tl_time = jiffies;
2467 if (!IS_ERR(tlink_tcon(tlink)))
2468 cifs_put_tcon(tlink_tcon(tlink));
2474 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2476 struct cifs_sb_info *old = CIFS_SB(sb);
2477 struct cifs_sb_info *new = mnt_data->cifs_sb;
2478 unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2479 unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2481 if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2484 if (old->mnt_cifs_serverino_autodisabled)
2485 newflags &= ~CIFS_MOUNT_SERVER_INUM;
2487 if (oldflags != newflags)
2491 * We want to share sb only if we don't specify an r/wsize or
2492 * specified r/wsize is greater than or equal to existing one.
2494 if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2497 if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2500 if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2501 !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2504 if (old->ctx->file_mode != new->ctx->file_mode ||
2505 old->ctx->dir_mode != new->ctx->dir_mode)
2508 if (strcmp(old->local_nls->charset, new->local_nls->charset))
2511 if (old->ctx->acregmax != new->ctx->acregmax)
2513 if (old->ctx->acdirmax != new->ctx->acdirmax)
2520 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2522 struct cifs_sb_info *old = CIFS_SB(sb);
2523 struct cifs_sb_info *new = mnt_data->cifs_sb;
2524 bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2526 bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2529 if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2531 else if (!old_set && !new_set)
2538 cifs_match_super(struct super_block *sb, void *data)
2540 struct cifs_mnt_data *mnt_data = (struct cifs_mnt_data *)data;
2541 struct smb3_fs_context *ctx;
2542 struct cifs_sb_info *cifs_sb;
2543 struct TCP_Server_Info *tcp_srv;
2544 struct cifs_ses *ses;
2545 struct cifs_tcon *tcon;
2546 struct tcon_link *tlink;
2549 spin_lock(&cifs_tcp_ses_lock);
2550 cifs_sb = CIFS_SB(sb);
2551 tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2552 if (tlink == NULL) {
2553 /* can not match superblock if tlink were ever null */
2554 spin_unlock(&cifs_tcp_ses_lock);
2557 tcon = tlink_tcon(tlink);
2559 tcp_srv = ses->server;
2561 ctx = mnt_data->ctx;
2563 if (!match_server(tcp_srv, ctx) ||
2564 !match_session(ses, ctx) ||
2565 !match_tcon(tcon, ctx) ||
2566 !match_prepath(sb, mnt_data)) {
2571 rc = compare_mount_options(sb, mnt_data);
2573 spin_unlock(&cifs_tcp_ses_lock);
2574 cifs_put_tlink(tlink);
2578 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2579 static struct lock_class_key cifs_key[2];
2580 static struct lock_class_key cifs_slock_key[2];
2583 cifs_reclassify_socket4(struct socket *sock)
2585 struct sock *sk = sock->sk;
2586 BUG_ON(!sock_allow_reclassification(sk));
2587 sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2588 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2592 cifs_reclassify_socket6(struct socket *sock)
2594 struct sock *sk = sock->sk;
2595 BUG_ON(!sock_allow_reclassification(sk));
2596 sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2597 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2601 cifs_reclassify_socket4(struct socket *sock)
2606 cifs_reclassify_socket6(struct socket *sock)
2611 /* See RFC1001 section 14 on representation of Netbios names */
2612 static void rfc1002mangle(char *target, char *source, unsigned int length)
2616 for (i = 0, j = 0; i < (length); i++) {
2617 /* mask a nibble at a time and encode */
2618 target[j] = 'A' + (0x0F & (source[i] >> 4));
2619 target[j+1] = 'A' + (0x0F & source[i]);
2626 bind_socket(struct TCP_Server_Info *server)
2629 if (server->srcaddr.ss_family != AF_UNSPEC) {
2630 /* Bind to the specified local IP address */
2631 struct socket *socket = server->ssocket;
2632 rc = socket->ops->bind(socket,
2633 (struct sockaddr *) &server->srcaddr,
2634 sizeof(server->srcaddr));
2636 struct sockaddr_in *saddr4;
2637 struct sockaddr_in6 *saddr6;
2638 saddr4 = (struct sockaddr_in *)&server->srcaddr;
2639 saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2640 if (saddr6->sin6_family == AF_INET6)
2641 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2642 &saddr6->sin6_addr, rc);
2644 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2645 &saddr4->sin_addr.s_addr, rc);
2652 ip_rfc1001_connect(struct TCP_Server_Info *server)
2656 * some servers require RFC1001 sessinit before sending
2657 * negprot - BB check reconnection in case where second
2658 * sessinit is sent but no second negprot
2660 struct rfc1002_session_packet *ses_init_buf;
2661 struct smb_hdr *smb_buf;
2662 ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
2665 ses_init_buf->trailer.session_req.called_len = 32;
2667 if (server->server_RFC1001_name[0] != 0)
2668 rfc1002mangle(ses_init_buf->trailer.
2669 session_req.called_name,
2670 server->server_RFC1001_name,
2671 RFC1001_NAME_LEN_WITH_NULL);
2673 rfc1002mangle(ses_init_buf->trailer.
2674 session_req.called_name,
2675 DEFAULT_CIFS_CALLED_NAME,
2676 RFC1001_NAME_LEN_WITH_NULL);
2678 ses_init_buf->trailer.session_req.calling_len = 32;
2681 * calling name ends in null (byte 16) from old smb
2684 if (server->workstation_RFC1001_name[0] != 0)
2685 rfc1002mangle(ses_init_buf->trailer.
2686 session_req.calling_name,
2687 server->workstation_RFC1001_name,
2688 RFC1001_NAME_LEN_WITH_NULL);
2690 rfc1002mangle(ses_init_buf->trailer.
2691 session_req.calling_name,
2693 RFC1001_NAME_LEN_WITH_NULL);
2695 ses_init_buf->trailer.session_req.scope1 = 0;
2696 ses_init_buf->trailer.session_req.scope2 = 0;
2697 smb_buf = (struct smb_hdr *)ses_init_buf;
2699 /* sizeof RFC1002_SESSION_REQUEST with no scope */
2700 smb_buf->smb_buf_length = cpu_to_be32(0x81000044);
2701 rc = smb_send(server, smb_buf, 0x44);
2702 kfree(ses_init_buf);
2704 * RFC1001 layer in at least one server
2705 * requires very short break before negprot
2706 * presumably because not expecting negprot
2707 * to follow so fast. This is a simple
2708 * solution that works without
2709 * complicating the code and causes no
2710 * significant slowing down on mount
2713 usleep_range(1000, 2000);
2716 * else the negprot may still work without this
2717 * even though malloc failed
2724 generic_ip_connect(struct TCP_Server_Info *server)
2729 struct socket *socket = server->ssocket;
2730 struct sockaddr *saddr;
2732 saddr = (struct sockaddr *) &server->dstaddr;
2734 if (server->dstaddr.ss_family == AF_INET6) {
2735 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
2737 sport = ipv6->sin6_port;
2738 slen = sizeof(struct sockaddr_in6);
2740 cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
2743 struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
2745 sport = ipv4->sin_port;
2746 slen = sizeof(struct sockaddr_in);
2748 cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
2752 if (socket == NULL) {
2753 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
2754 IPPROTO_TCP, &socket, 1);
2756 cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
2757 server->ssocket = NULL;
2761 /* BB other socket options to set KEEPALIVE, NODELAY? */
2762 cifs_dbg(FYI, "Socket created\n");
2763 server->ssocket = socket;
2764 socket->sk->sk_allocation = GFP_NOFS;
2765 if (sfamily == AF_INET6)
2766 cifs_reclassify_socket6(socket);
2768 cifs_reclassify_socket4(socket);
2771 rc = bind_socket(server);
2776 * Eventually check for other socket options to change from
2777 * the default. sock_setsockopt not used because it expects
2780 socket->sk->sk_rcvtimeo = 7 * HZ;
2781 socket->sk->sk_sndtimeo = 5 * HZ;
2783 /* make the bufsizes depend on wsize/rsize and max requests */
2784 if (server->noautotune) {
2785 if (socket->sk->sk_sndbuf < (200 * 1024))
2786 socket->sk->sk_sndbuf = 200 * 1024;
2787 if (socket->sk->sk_rcvbuf < (140 * 1024))
2788 socket->sk->sk_rcvbuf = 140 * 1024;
2791 if (server->tcp_nodelay)
2792 tcp_sock_set_nodelay(socket->sk);
2794 cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
2795 socket->sk->sk_sndbuf,
2796 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
2798 rc = socket->ops->connect(socket, saddr, slen,
2799 server->noblockcnt ? O_NONBLOCK : 0);
2801 * When mounting SMB root file systems, we do not want to block in
2802 * connect. Otherwise bail out and then let cifs_reconnect() perform
2803 * reconnect failover - if possible.
2805 if (server->noblockcnt && rc == -EINPROGRESS)
2808 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
2809 trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
2810 sock_release(socket);
2811 server->ssocket = NULL;
2814 trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
2815 if (sport == htons(RFC1001_PORT))
2816 rc = ip_rfc1001_connect(server);
2822 ip_connect(struct TCP_Server_Info *server)
2825 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2826 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2828 if (server->dstaddr.ss_family == AF_INET6)
2829 sport = &addr6->sin6_port;
2831 sport = &addr->sin_port;
2836 /* try with 445 port at first */
2837 *sport = htons(CIFS_PORT);
2839 rc = generic_ip_connect(server);
2843 /* if it failed, try with 139 port */
2844 *sport = htons(RFC1001_PORT);
2847 return generic_ip_connect(server);
2850 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
2851 struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
2854 * If we are reconnecting then should we check to see if
2855 * any requested capabilities changed locally e.g. via
2856 * remount but we can not do much about it here
2857 * if they have (even if we could detect it by the following)
2858 * Perhaps we could add a backpointer to array of sb from tcon
2859 * or if we change to make all sb to same share the same
2860 * sb as NFS - then we only have one backpointer to sb.
2861 * What if we wanted to mount the server share twice once with
2862 * and once without posixacls or posix paths?
2864 __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
2866 if (ctx && ctx->no_linux_ext) {
2867 tcon->fsUnixInfo.Capability = 0;
2868 tcon->unix_ext = 0; /* Unix Extensions disabled */
2869 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
2872 tcon->unix_ext = 1; /* Unix Extensions supported */
2874 if (!tcon->unix_ext) {
2875 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
2879 if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
2880 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
2881 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
2883 * check for reconnect case in which we do not
2884 * want to change the mount behavior if we can avoid it
2888 * turn off POSIX ACL and PATHNAMES if not set
2889 * originally at mount time
2891 if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
2892 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
2893 if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
2894 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
2895 cifs_dbg(VFS, "POSIXPATH support change\n");
2896 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
2897 } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
2898 cifs_dbg(VFS, "possible reconnect error\n");
2899 cifs_dbg(VFS, "server disabled POSIX path support\n");
2903 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
2904 cifs_dbg(VFS, "per-share encryption not supported yet\n");
2906 cap &= CIFS_UNIX_CAP_MASK;
2907 if (ctx && ctx->no_psx_acl)
2908 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
2909 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
2910 cifs_dbg(FYI, "negotiated posix acl support\n");
2912 cifs_sb->mnt_cifs_flags |=
2913 CIFS_MOUNT_POSIXACL;
2916 if (ctx && ctx->posix_paths == 0)
2917 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
2918 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
2919 cifs_dbg(FYI, "negotiate posix pathnames\n");
2921 cifs_sb->mnt_cifs_flags |=
2922 CIFS_MOUNT_POSIX_PATHS;
2925 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
2926 #ifdef CONFIG_CIFS_DEBUG2
2927 if (cap & CIFS_UNIX_FCNTL_CAP)
2928 cifs_dbg(FYI, "FCNTL cap\n");
2929 if (cap & CIFS_UNIX_EXTATTR_CAP)
2930 cifs_dbg(FYI, "EXTATTR cap\n");
2931 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
2932 cifs_dbg(FYI, "POSIX path cap\n");
2933 if (cap & CIFS_UNIX_XATTR_CAP)
2934 cifs_dbg(FYI, "XATTR cap\n");
2935 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
2936 cifs_dbg(FYI, "POSIX ACL cap\n");
2937 if (cap & CIFS_UNIX_LARGE_READ_CAP)
2938 cifs_dbg(FYI, "very large read cap\n");
2939 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
2940 cifs_dbg(FYI, "very large write cap\n");
2941 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
2942 cifs_dbg(FYI, "transport encryption cap\n");
2943 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
2944 cifs_dbg(FYI, "mandatory transport encryption cap\n");
2945 #endif /* CIFS_DEBUG2 */
2946 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
2948 cifs_dbg(FYI, "resetting capabilities failed\n");
2950 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");
2956 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
2958 struct smb3_fs_context *ctx = cifs_sb->ctx;
2960 INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
2962 spin_lock_init(&cifs_sb->tlink_tree_lock);
2963 cifs_sb->tlink_tree = RB_ROOT;
2965 cifs_dbg(FYI, "file mode: %04ho dir mode: %04ho\n",
2966 ctx->file_mode, ctx->dir_mode);
2968 /* this is needed for ASCII cp to Unicode converts */
2969 if (ctx->iocharset == NULL) {
2970 /* load_nls_default cannot return null */
2971 cifs_sb->local_nls = load_nls_default();
2973 cifs_sb->local_nls = load_nls(ctx->iocharset);
2974 if (cifs_sb->local_nls == NULL) {
2975 cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
2980 ctx->local_nls = cifs_sb->local_nls;
2982 smb3_update_mnt_flags(cifs_sb);
2985 cifs_dbg(FYI, "mounting share using direct i/o\n");
2986 if (ctx->cache_ro) {
2987 cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
2988 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
2989 } else if (ctx->cache_rw) {
2990 cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
2991 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
2992 CIFS_MOUNT_RW_CACHE);
2995 if ((ctx->cifs_acl) && (ctx->dynperm))
2996 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
2999 cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3000 if (cifs_sb->prepath == NULL)
3002 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3008 /* Release all succeed connections */
3009 static inline void mount_put_conns(struct mount_ctx *mnt_ctx)
3014 cifs_put_tcon(mnt_ctx->tcon);
3015 else if (mnt_ctx->ses)
3016 cifs_put_smb_ses(mnt_ctx->ses);
3017 else if (mnt_ctx->server)
3018 cifs_put_tcp_session(mnt_ctx->server, 0);
3019 mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3020 free_xid(mnt_ctx->xid);
3023 /* Get connections for tcp, ses and tcon */
3024 static int mount_get_conns(struct mount_ctx *mnt_ctx)
3027 struct TCP_Server_Info *server = NULL;
3028 struct cifs_ses *ses = NULL;
3029 struct cifs_tcon *tcon = NULL;
3030 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3031 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3036 /* get a reference to a tcp session */
3037 server = cifs_get_tcp_session(ctx, NULL);
3038 if (IS_ERR(server)) {
3039 rc = PTR_ERR(server);
3044 /* get a reference to a SMB session */
3045 ses = cifs_get_smb_ses(server, ctx);
3052 if ((ctx->persistent == true) && (!(ses->server->capabilities &
3053 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3054 cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3059 /* search for existing tcon to this server share */
3060 tcon = cifs_get_tcon(ses, ctx);
3067 /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3068 if (tcon->posix_extensions)
3069 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3071 /* tell server which Unix caps we support */
3072 if (cap_unix(tcon->ses)) {
3074 * reset of caps checks mount to see if unix extensions disabled
3075 * for just this mount.
3077 reset_cifs_unix_caps(xid, tcon, cifs_sb, ctx);
3078 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3079 (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3080 CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3085 tcon->unix_ext = 0; /* server does not support them */
3087 /* do not care if a following call succeed - informational */
3088 if (!tcon->pipe && server->ops->qfs_tcon) {
3089 server->ops->qfs_tcon(xid, tcon, cifs_sb);
3090 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3091 if (tcon->fsDevInfo.DeviceCharacteristics &
3092 cpu_to_le32(FILE_READ_ONLY_DEVICE))
3093 cifs_dbg(VFS, "mounted to read only share\n");
3094 else if ((cifs_sb->mnt_cifs_flags &
3095 CIFS_MOUNT_RW_CACHE) == 0)
3096 cifs_dbg(VFS, "read only mount of RW share\n");
3097 /* no need to log a RW mount of a typical RW share */
3102 * Clamp the rsize/wsize mount arguments if they are too big for the server
3103 * and set the rsize/wsize to the negotiated values if not passed in by
3106 if ((cifs_sb->ctx->wsize == 0) ||
3107 (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
3108 cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
3109 if ((cifs_sb->ctx->rsize == 0) ||
3110 (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3111 cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3114 * The cookie is initialized from volume info returned above.
3115 * Inside cifs_fscache_get_super_cookie it checks
3116 * that we do not get super cookie twice.
3118 cifs_fscache_get_super_cookie(tcon);
3121 mnt_ctx->server = server;
3123 mnt_ctx->tcon = tcon;
3129 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3130 struct cifs_tcon *tcon)
3132 struct tcon_link *tlink;
3134 /* hang the tcon off of the superblock */
3135 tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3139 tlink->tl_uid = ses->linux_uid;
3140 tlink->tl_tcon = tcon;
3141 tlink->tl_time = jiffies;
3142 set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3143 set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3145 cifs_sb->master_tlink = tlink;
3146 spin_lock(&cifs_sb->tlink_tree_lock);
3147 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3148 spin_unlock(&cifs_sb->tlink_tree_lock);
3150 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3155 #ifdef CONFIG_CIFS_DFS_UPCALL
3156 /* Get unique dfs connections */
3157 static int mount_get_dfs_conns(struct mount_ctx *mnt_ctx)
3161 mnt_ctx->fs_ctx->nosharesock = true;
3162 rc = mount_get_conns(mnt_ctx);
3163 if (mnt_ctx->server) {
3164 cifs_dbg(FYI, "%s: marking tcp session as a dfs connection\n", __func__);
3165 spin_lock(&cifs_tcp_ses_lock);
3166 mnt_ctx->server->is_dfs_conn = true;
3167 spin_unlock(&cifs_tcp_ses_lock);
3173 * cifs_build_path_to_root returns full path to root when we do not have an
3174 * existing connection (tcon)
3177 build_unc_path_to_root(const struct smb3_fs_context *ctx,
3178 const struct cifs_sb_info *cifs_sb, bool useppath)
3180 char *full_path, *pos;
3181 unsigned int pplen = useppath && ctx->prepath ?
3182 strlen(ctx->prepath) + 1 : 0;
3183 unsigned int unc_len = strnlen(ctx->UNC, MAX_TREE_SIZE + 1);
3185 if (unc_len > MAX_TREE_SIZE)
3186 return ERR_PTR(-EINVAL);
3188 full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
3189 if (full_path == NULL)
3190 return ERR_PTR(-ENOMEM);
3192 memcpy(full_path, ctx->UNC, unc_len);
3193 pos = full_path + unc_len;
3196 *pos = CIFS_DIR_SEP(cifs_sb);
3197 memcpy(pos + 1, ctx->prepath, pplen);
3201 *pos = '\0'; /* add trailing null */
3202 convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
3203 cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
3208 * expand_dfs_referral - Update cifs_sb from dfs referral path
3210 * cifs_sb->ctx->mount_options will be (re-)allocated to a string containing updated options for the
3211 * submount. Otherwise it will be left untouched.
3213 static int expand_dfs_referral(struct mount_ctx *mnt_ctx, const char *full_path,
3214 struct dfs_info3_param *referral)
3217 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3218 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3219 char *fake_devname = NULL, *mdata = NULL;
3221 mdata = cifs_compose_mount_options(cifs_sb->ctx->mount_options, full_path + 1, referral,
3223 if (IS_ERR(mdata)) {
3224 rc = PTR_ERR(mdata);
3228 * We can not clear out the whole structure since we no longer have an explicit
3229 * function to parse a mount-string. Instead we need to clear out the individual
3230 * fields that are no longer valid.
3232 kfree(ctx->prepath);
3233 ctx->prepath = NULL;
3234 rc = cifs_setup_volume_info(ctx, mdata, fake_devname);
3236 kfree(fake_devname);
3237 kfree(cifs_sb->ctx->mount_options);
3238 cifs_sb->ctx->mount_options = mdata;
3244 /* TODO: all callers to this are broken. We are not parsing mount_options here
3245 * we should pass a clone of the original context?
3248 cifs_setup_volume_info(struct smb3_fs_context *ctx, const char *mntopts, const char *devname)
3253 cifs_dbg(FYI, "%s: devname=%s\n", __func__, devname);
3254 rc = smb3_parse_devname(devname, ctx);
3256 cifs_dbg(VFS, "%s: failed to parse %s: %d\n", __func__, devname, rc);
3264 rc = smb3_parse_opt(mntopts, "ip", &ip);
3266 cifs_dbg(VFS, "%s: failed to parse ip options: %d\n", __func__, rc);
3270 rc = cifs_convert_address((struct sockaddr *)&ctx->dstaddr, ip, strlen(ip));
3273 cifs_dbg(VFS, "%s: failed to convert ip address\n", __func__);
3278 if (ctx->nullauth) {
3279 cifs_dbg(FYI, "Anonymous login\n");
3280 kfree(ctx->username);
3281 ctx->username = NULL;
3282 } else if (ctx->username) {
3283 /* BB fixme parse for domain name here */
3284 cifs_dbg(FYI, "Username: %s\n", ctx->username);
3286 cifs_dbg(VFS, "No username specified\n");
3287 /* In userspace mount helper we can get user name from alternate
3288 locations such as env variables and files on disk */
3296 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3298 struct cifs_tcon *tcon,
3299 struct cifs_sb_info *cifs_sb,
3306 int skip = added_treename ? 1 : 0;
3308 sep = CIFS_DIR_SEP(cifs_sb);
3311 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3313 /* skip separators */
3318 /* next separator */
3319 while (*s && *s != sep)
3322 * if the treename is added, we then have to skip the first
3323 * part within the separators
3330 * temporarily null-terminate the path at the end of
3331 * the current component
3335 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3343 * Check if path is remote (e.g. a DFS share). Return -EREMOTE if it is,
3346 static int is_path_remote(struct mount_ctx *mnt_ctx)
3349 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3350 struct TCP_Server_Info *server = mnt_ctx->server;
3351 unsigned int xid = mnt_ctx->xid;
3352 struct cifs_tcon *tcon = mnt_ctx->tcon;
3353 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3356 if (!server->ops->is_path_accessible)
3360 * cifs_build_path_to_root works only when we have a valid tcon
3362 full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3363 tcon->Flags & SMB_SHARE_IS_IN_DFS);
3364 if (full_path == NULL)
3367 cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3369 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3371 if (rc != 0 && rc != -EREMOTE) {
3376 if (rc != -EREMOTE) {
3377 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3378 cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3380 cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3381 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3390 #ifdef CONFIG_CIFS_DFS_UPCALL
3391 static void set_root_ses(struct mount_ctx *mnt_ctx)
3394 spin_lock(&cifs_tcp_ses_lock);
3395 mnt_ctx->ses->ses_count++;
3396 spin_unlock(&cifs_tcp_ses_lock);
3397 dfs_cache_add_refsrv_session(&mnt_ctx->mount_id, mnt_ctx->ses);
3399 mnt_ctx->root_ses = mnt_ctx->ses;
3402 static int is_dfs_mount(struct mount_ctx *mnt_ctx, bool *isdfs, struct dfs_cache_tgt_list *root_tl)
3405 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3406 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3410 rc = mount_get_conns(mnt_ctx);
3412 * If called with 'nodfs' mount option, then skip DFS resolving. Otherwise unconditionally
3413 * try to get an DFS referral (even cached) to determine whether it is an DFS mount.
3415 * Skip prefix path to provide support for DFS referrals from w2k8 servers which don't seem
3416 * to respond with PATH_NOT_COVERED to requests that include the prefix.
3418 if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
3419 dfs_cache_find(mnt_ctx->xid, mnt_ctx->ses, cifs_sb->local_nls, cifs_remap(cifs_sb),
3420 ctx->UNC + 1, NULL, root_tl)) {
3423 /* Check if it is fully accessible and then mount it */
3424 rc = is_path_remote(mnt_ctx);
3427 else if (rc != -EREMOTE)
3433 static int connect_dfs_target(struct mount_ctx *mnt_ctx, const char *full_path,
3434 const char *ref_path, struct dfs_cache_tgt_iterator *tit)
3437 struct dfs_info3_param ref = {};
3438 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3439 char *oldmnt = cifs_sb->ctx->mount_options;
3441 rc = dfs_cache_get_tgt_referral(ref_path, tit, &ref);
3445 rc = expand_dfs_referral(mnt_ctx, full_path, &ref);
3449 /* Connect to new target only if we were redirected (e.g. mount options changed) */
3450 if (oldmnt != cifs_sb->ctx->mount_options) {
3451 mount_put_conns(mnt_ctx);
3452 rc = mount_get_dfs_conns(mnt_ctx);
3455 if (cifs_is_referral_server(mnt_ctx->tcon, &ref))
3456 set_root_ses(mnt_ctx);
3457 rc = dfs_cache_update_tgthint(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3458 cifs_remap(cifs_sb), ref_path, tit);
3462 free_dfs_info_param(&ref);
3466 static int connect_dfs_root(struct mount_ctx *mnt_ctx, struct dfs_cache_tgt_list *root_tl)
3470 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3471 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3472 struct dfs_cache_tgt_iterator *tit;
3474 /* Put initial connections as they might be shared with other mounts. We need unique dfs
3475 * connections per mount to properly failover, so mount_get_dfs_conns() must be used from
3478 mount_put_conns(mnt_ctx);
3479 mount_get_dfs_conns(mnt_ctx);
3480 set_root_ses(mnt_ctx);
3482 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3483 if (IS_ERR(full_path))
3484 return PTR_ERR(full_path);
3486 mnt_ctx->origin_fullpath = dfs_cache_canonical_path(ctx->UNC, cifs_sb->local_nls,
3487 cifs_remap(cifs_sb));
3488 if (IS_ERR(mnt_ctx->origin_fullpath)) {
3489 rc = PTR_ERR(mnt_ctx->origin_fullpath);
3490 mnt_ctx->origin_fullpath = NULL;
3494 /* Try all dfs root targets */
3495 for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(root_tl);
3496 tit; tit = dfs_cache_get_next_tgt(root_tl, tit)) {
3497 rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->origin_fullpath + 1, tit);
3499 mnt_ctx->leaf_fullpath = kstrdup(mnt_ctx->origin_fullpath, GFP_KERNEL);
3500 if (!mnt_ctx->leaf_fullpath)
3511 static int __follow_dfs_link(struct mount_ctx *mnt_ctx)
3514 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3515 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3517 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3518 struct dfs_cache_tgt_iterator *tit;
3520 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3521 if (IS_ERR(full_path))
3522 return PTR_ERR(full_path);
3524 kfree(mnt_ctx->leaf_fullpath);
3525 mnt_ctx->leaf_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3526 cifs_remap(cifs_sb));
3527 if (IS_ERR(mnt_ctx->leaf_fullpath)) {
3528 rc = PTR_ERR(mnt_ctx->leaf_fullpath);
3529 mnt_ctx->leaf_fullpath = NULL;
3533 /* Get referral from dfs link */
3534 rc = dfs_cache_find(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3535 cifs_remap(cifs_sb), mnt_ctx->leaf_fullpath + 1, NULL, &tl);
3539 /* Try all dfs link targets */
3540 for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(&tl);
3541 tit; tit = dfs_cache_get_next_tgt(&tl, tit)) {
3542 rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->leaf_fullpath + 1, tit);
3544 rc = is_path_remote(mnt_ctx);
3551 dfs_cache_free_tgts(&tl);
3555 static int follow_dfs_link(struct mount_ctx *mnt_ctx)
3558 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3559 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3563 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3564 if (IS_ERR(full_path))
3565 return PTR_ERR(full_path);
3567 kfree(mnt_ctx->origin_fullpath);
3568 mnt_ctx->origin_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3569 cifs_remap(cifs_sb));
3572 if (IS_ERR(mnt_ctx->origin_fullpath)) {
3573 rc = PTR_ERR(mnt_ctx->origin_fullpath);
3574 mnt_ctx->origin_fullpath = NULL;
3579 rc = __follow_dfs_link(mnt_ctx);
3580 if (!rc || rc != -EREMOTE)
3582 } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
3587 /* Set up DFS referral paths for failover */
3588 static void setup_server_referral_paths(struct mount_ctx *mnt_ctx)
3590 struct TCP_Server_Info *server = mnt_ctx->server;
3592 server->origin_fullpath = mnt_ctx->origin_fullpath;
3593 server->leaf_fullpath = mnt_ctx->leaf_fullpath;
3594 server->current_fullpath = mnt_ctx->leaf_fullpath;
3595 mnt_ctx->origin_fullpath = mnt_ctx->leaf_fullpath = NULL;
3598 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3601 struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3602 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3605 rc = is_dfs_mount(&mnt_ctx, &isdfs, &tl);
3611 uuid_gen(&mnt_ctx.mount_id);
3612 rc = connect_dfs_root(&mnt_ctx, &tl);
3613 dfs_cache_free_tgts(&tl);
3618 rc = is_path_remote(&mnt_ctx);
3620 rc = follow_dfs_link(&mnt_ctx);
3624 setup_server_referral_paths(&mnt_ctx);
3626 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3627 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3629 cifs_autodisable_serverino(cifs_sb);
3631 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3632 * that have different prefix paths.
3634 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3635 kfree(cifs_sb->prepath);
3636 cifs_sb->prepath = ctx->prepath;
3637 ctx->prepath = NULL;
3638 uuid_copy(&cifs_sb->dfs_mount_id, &mnt_ctx.mount_id);
3641 free_xid(mnt_ctx.xid);
3642 cifs_try_adding_channels(cifs_sb, mnt_ctx.ses);
3643 return mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3646 dfs_cache_put_refsrv_sessions(&mnt_ctx.mount_id);
3647 kfree(mnt_ctx.origin_fullpath);
3648 kfree(mnt_ctx.leaf_fullpath);
3649 mount_put_conns(&mnt_ctx);
3653 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3656 struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3658 rc = mount_get_conns(&mnt_ctx);
3663 rc = is_path_remote(&mnt_ctx);
3670 free_xid(mnt_ctx.xid);
3671 return mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3674 mount_put_conns(&mnt_ctx);
3680 * Issue a TREE_CONNECT request.
3683 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3684 const char *tree, struct cifs_tcon *tcon,
3685 const struct nls_table *nls_codepage)
3687 struct smb_hdr *smb_buffer;
3688 struct smb_hdr *smb_buffer_response;
3691 unsigned char *bcc_ptr;
3694 __u16 bytes_left, count;
3699 smb_buffer = cifs_buf_get();
3700 if (smb_buffer == NULL)
3703 smb_buffer_response = smb_buffer;
3705 header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3706 NULL /*no tid */ , 4 /*wct */ );
3708 smb_buffer->Mid = get_next_mid(ses->server);
3709 smb_buffer->Uid = ses->Suid;
3710 pSMB = (TCONX_REQ *) smb_buffer;
3711 pSMBr = (TCONX_RSP *) smb_buffer_response;
3713 pSMB->AndXCommand = 0xFF;
3714 pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3715 bcc_ptr = &pSMB->Password[0];
3716 if (tcon->pipe || (ses->server->sec_mode & SECMODE_USER)) {
3717 pSMB->PasswordLength = cpu_to_le16(1); /* minimum */
3718 *bcc_ptr = 0; /* password is null byte */
3719 bcc_ptr++; /* skip password */
3720 /* already aligned so no need to do it below */
3723 if (ses->server->sign)
3724 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3726 if (ses->capabilities & CAP_STATUS32) {
3727 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3729 if (ses->capabilities & CAP_DFS) {
3730 smb_buffer->Flags2 |= SMBFLG2_DFS;
3732 if (ses->capabilities & CAP_UNICODE) {
3733 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3735 cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3736 6 /* max utf8 char length in bytes */ *
3737 (/* server len*/ + 256 /* share len */), nls_codepage);
3738 bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */
3739 bcc_ptr += 2; /* skip trailing null */
3740 } else { /* ASCII */
3741 strcpy(bcc_ptr, tree);
3742 bcc_ptr += strlen(tree) + 1;
3744 strcpy(bcc_ptr, "?????");
3745 bcc_ptr += strlen("?????");
3747 count = bcc_ptr - &pSMB->Password[0];
3748 be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3749 pSMB->ByteCount = cpu_to_le16(count);
3751 rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3754 /* above now done in SendReceive */
3758 tcon->tidStatus = CifsGood;
3759 tcon->need_reconnect = false;
3760 tcon->tid = smb_buffer_response->Tid;
3761 bcc_ptr = pByteArea(smb_buffer_response);
3762 bytes_left = get_bcc(smb_buffer_response);
3763 length = strnlen(bcc_ptr, bytes_left - 2);
3764 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3770 /* skip service field (NB: this field is always ASCII) */
3772 if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3773 (bcc_ptr[2] == 'C')) {
3774 cifs_dbg(FYI, "IPC connection\n");
3778 } else if (length == 2) {
3779 if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3780 /* the most common case */
3781 cifs_dbg(FYI, "disk share connection\n");
3784 bcc_ptr += length + 1;
3785 bytes_left -= (length + 1);
3786 strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
3788 /* mostly informational -- no need to fail on error here */
3789 kfree(tcon->nativeFileSystem);
3790 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3791 bytes_left, is_unicode,
3794 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3796 if ((smb_buffer_response->WordCount == 3) ||
3797 (smb_buffer_response->WordCount == 7))
3798 /* field is in same location */
3799 tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3802 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3805 cifs_buf_release(smb_buffer);
3809 static void delayed_free(struct rcu_head *p)
3811 struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
3813 unload_nls(cifs_sb->local_nls);
3814 smb3_cleanup_fs_context(cifs_sb->ctx);
3819 cifs_umount(struct cifs_sb_info *cifs_sb)
3821 struct rb_root *root = &cifs_sb->tlink_tree;
3822 struct rb_node *node;
3823 struct tcon_link *tlink;
3825 cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3827 spin_lock(&cifs_sb->tlink_tree_lock);
3828 while ((node = rb_first(root))) {
3829 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3830 cifs_get_tlink(tlink);
3831 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3832 rb_erase(node, root);
3834 spin_unlock(&cifs_sb->tlink_tree_lock);
3835 cifs_put_tlink(tlink);
3836 spin_lock(&cifs_sb->tlink_tree_lock);
3838 spin_unlock(&cifs_sb->tlink_tree_lock);
3840 kfree(cifs_sb->prepath);
3841 #ifdef CONFIG_CIFS_DFS_UPCALL
3842 dfs_cache_put_refsrv_sessions(&cifs_sb->dfs_mount_id);
3844 call_rcu(&cifs_sb->rcu, delayed_free);
3848 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
3849 struct TCP_Server_Info *server)
3853 if (!server->ops->need_neg || !server->ops->negotiate)
3856 /* only send once per connect */
3857 if (!server->ops->need_neg(server))
3860 rc = server->ops->negotiate(xid, ses, server);
3862 spin_lock(&GlobalMid_Lock);
3863 if (server->tcpStatus == CifsNeedNegotiate)
3864 server->tcpStatus = CifsGood;
3867 spin_unlock(&GlobalMid_Lock);
3874 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
3875 struct TCP_Server_Info *server,
3876 struct nls_table *nls_info)
3879 bool is_binding = false;
3881 spin_lock(&ses->chan_lock);
3882 is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
3883 spin_unlock(&ses->chan_lock);
3886 ses->capabilities = server->capabilities;
3887 if (!linuxExtEnabled)
3888 ses->capabilities &= (~server->vals->cap_unix);
3890 if (ses->auth_key.response) {
3891 cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
3892 ses->auth_key.response);
3893 kfree(ses->auth_key.response);
3894 ses->auth_key.response = NULL;
3895 ses->auth_key.len = 0;
3899 cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
3900 server->sec_mode, server->capabilities, server->timeAdj);
3902 if (server->ops->sess_setup)
3903 rc = server->ops->sess_setup(xid, ses, server, nls_info);
3906 cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
3912 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
3914 ctx->sectype = ses->sectype;
3916 /* krb5 is special, since we don't need username or pw */
3917 if (ctx->sectype == Kerberos)
3920 return cifs_set_cifscreds(ctx, ses);
3923 static struct cifs_tcon *
3924 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
3927 struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
3928 struct cifs_ses *ses;
3929 struct cifs_tcon *tcon = NULL;
3930 struct smb3_fs_context *ctx;
3932 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3934 return ERR_PTR(-ENOMEM);
3936 ctx->local_nls = cifs_sb->local_nls;
3937 ctx->linux_uid = fsuid;
3938 ctx->cred_uid = fsuid;
3939 ctx->UNC = master_tcon->treeName;
3940 ctx->retry = master_tcon->retry;
3941 ctx->nocase = master_tcon->nocase;
3942 ctx->nohandlecache = master_tcon->nohandlecache;
3943 ctx->local_lease = master_tcon->local_lease;
3944 ctx->no_lease = master_tcon->no_lease;
3945 ctx->resilient = master_tcon->use_resilient;
3946 ctx->persistent = master_tcon->use_persistent;
3947 ctx->handle_timeout = master_tcon->handle_timeout;
3948 ctx->no_linux_ext = !master_tcon->unix_ext;
3949 ctx->linux_ext = master_tcon->posix_extensions;
3950 ctx->sectype = master_tcon->ses->sectype;
3951 ctx->sign = master_tcon->ses->sign;
3952 ctx->seal = master_tcon->seal;
3953 ctx->witness = master_tcon->use_witness;
3955 rc = cifs_set_vol_auth(ctx, master_tcon->ses);
3961 /* get a reference for the same TCP session */
3962 spin_lock(&cifs_tcp_ses_lock);
3963 ++master_tcon->ses->server->srv_count;
3964 spin_unlock(&cifs_tcp_ses_lock);
3966 ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
3968 tcon = (struct cifs_tcon *)ses;
3969 cifs_put_tcp_session(master_tcon->ses->server, 0);
3973 tcon = cifs_get_tcon(ses, ctx);
3975 cifs_put_smb_ses(ses);
3980 reset_cifs_unix_caps(0, tcon, NULL, ctx);
3983 kfree(ctx->username);
3984 kfree_sensitive(ctx->password);
3991 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
3993 return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
3996 /* find and return a tlink with given uid */
3997 static struct tcon_link *
3998 tlink_rb_search(struct rb_root *root, kuid_t uid)
4000 struct rb_node *node = root->rb_node;
4001 struct tcon_link *tlink;
4004 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4006 if (uid_gt(tlink->tl_uid, uid))
4007 node = node->rb_left;
4008 else if (uid_lt(tlink->tl_uid, uid))
4009 node = node->rb_right;
4016 /* insert a tcon_link into the tree */
4018 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4020 struct rb_node **new = &(root->rb_node), *parent = NULL;
4021 struct tcon_link *tlink;
4024 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4027 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4028 new = &((*new)->rb_left);
4030 new = &((*new)->rb_right);
4033 rb_link_node(&new_tlink->tl_rbnode, parent, new);
4034 rb_insert_color(&new_tlink->tl_rbnode, root);
4038 * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4041 * If the superblock doesn't refer to a multiuser mount, then just return
4042 * the master tcon for the mount.
4044 * First, search the rbtree for an existing tcon for this fsuid. If one
4045 * exists, then check to see if it's pending construction. If it is then wait
4046 * for construction to complete. Once it's no longer pending, check to see if
4047 * it failed and either return an error or retry construction, depending on
4050 * If one doesn't exist then insert a new tcon_link struct into the tree and
4051 * try to construct a new one.
4054 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4057 kuid_t fsuid = current_fsuid();
4058 struct tcon_link *tlink, *newtlink;
4060 if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4061 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4063 spin_lock(&cifs_sb->tlink_tree_lock);
4064 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4066 cifs_get_tlink(tlink);
4067 spin_unlock(&cifs_sb->tlink_tree_lock);
4069 if (tlink == NULL) {
4070 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4071 if (newtlink == NULL)
4072 return ERR_PTR(-ENOMEM);
4073 newtlink->tl_uid = fsuid;
4074 newtlink->tl_tcon = ERR_PTR(-EACCES);
4075 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4076 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4077 cifs_get_tlink(newtlink);
4079 spin_lock(&cifs_sb->tlink_tree_lock);
4080 /* was one inserted after previous search? */
4081 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4083 cifs_get_tlink(tlink);
4084 spin_unlock(&cifs_sb->tlink_tree_lock);
4086 goto wait_for_construction;
4089 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4090 spin_unlock(&cifs_sb->tlink_tree_lock);
4092 wait_for_construction:
4093 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4094 TASK_INTERRUPTIBLE);
4096 cifs_put_tlink(tlink);
4097 return ERR_PTR(-ERESTARTSYS);
4100 /* if it's good, return it */
4101 if (!IS_ERR(tlink->tl_tcon))
4104 /* return error if we tried this already recently */
4105 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4106 cifs_put_tlink(tlink);
4107 return ERR_PTR(-EACCES);
4110 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4111 goto wait_for_construction;
4114 tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4115 clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4116 wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4118 if (IS_ERR(tlink->tl_tcon)) {
4119 cifs_put_tlink(tlink);
4120 return ERR_PTR(-EACCES);
4127 * periodic workqueue job that scans tcon_tree for a superblock and closes
4131 cifs_prune_tlinks(struct work_struct *work)
4133 struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4135 struct rb_root *root = &cifs_sb->tlink_tree;
4136 struct rb_node *node;
4137 struct rb_node *tmp;
4138 struct tcon_link *tlink;
4141 * Because we drop the spinlock in the loop in order to put the tlink
4142 * it's not guarded against removal of links from the tree. The only
4143 * places that remove entries from the tree are this function and
4144 * umounts. Because this function is non-reentrant and is canceled
4145 * before umount can proceed, this is safe.
4147 spin_lock(&cifs_sb->tlink_tree_lock);
4148 node = rb_first(root);
4149 while (node != NULL) {
4151 node = rb_next(tmp);
4152 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4154 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4155 atomic_read(&tlink->tl_count) != 0 ||
4156 time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4159 cifs_get_tlink(tlink);
4160 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4161 rb_erase(tmp, root);
4163 spin_unlock(&cifs_sb->tlink_tree_lock);
4164 cifs_put_tlink(tlink);
4165 spin_lock(&cifs_sb->tlink_tree_lock);
4167 spin_unlock(&cifs_sb->tlink_tree_lock);
4169 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4173 #ifdef CONFIG_CIFS_DFS_UPCALL
4174 /* Update dfs referral path of superblock */
4175 static int update_server_fullpath(struct TCP_Server_Info *server, struct cifs_sb_info *cifs_sb,
4179 size_t len = strlen(target);
4180 char *refpath, *npath;
4182 if (unlikely(len < 2 || *target != '\\'))
4185 if (target[1] == '\\') {
4187 refpath = kmalloc(len, GFP_KERNEL);
4191 scnprintf(refpath, len, "%s", target);
4193 len += sizeof("\\");
4194 refpath = kmalloc(len, GFP_KERNEL);
4198 scnprintf(refpath, len, "\\%s", target);
4201 npath = dfs_cache_canonical_path(refpath, cifs_sb->local_nls, cifs_remap(cifs_sb));
4204 if (IS_ERR(npath)) {
4205 rc = PTR_ERR(npath);
4207 mutex_lock(&server->refpath_lock);
4208 kfree(server->leaf_fullpath);
4209 server->leaf_fullpath = npath;
4210 mutex_unlock(&server->refpath_lock);
4211 server->current_fullpath = server->leaf_fullpath;
4216 static int target_share_matches_server(struct TCP_Server_Info *server, const char *tcp_host,
4217 size_t tcp_host_len, char *share, bool *target_match)
4220 const char *dfs_host;
4221 size_t dfs_host_len;
4223 *target_match = true;
4224 extract_unc_hostname(share, &dfs_host, &dfs_host_len);
4226 /* Check if hostnames or addresses match */
4227 if (dfs_host_len != tcp_host_len || strncasecmp(dfs_host, tcp_host, dfs_host_len) != 0) {
4228 cifs_dbg(FYI, "%s: %.*s doesn't match %.*s\n", __func__, (int)dfs_host_len,
4229 dfs_host, (int)tcp_host_len, tcp_host);
4230 rc = match_target_ip(server, dfs_host, dfs_host_len, target_match);
4232 cifs_dbg(VFS, "%s: failed to match target ip: %d\n", __func__, rc);
4237 static int __tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4238 struct cifs_sb_info *cifs_sb, char *tree, bool islink,
4239 struct dfs_cache_tgt_list *tl)
4242 struct TCP_Server_Info *server = tcon->ses->server;
4243 const struct smb_version_operations *ops = server->ops;
4244 struct cifs_tcon *ipc = tcon->ses->tcon_ipc;
4245 char *share = NULL, *prefix = NULL;
4246 const char *tcp_host;
4247 size_t tcp_host_len;
4248 struct dfs_cache_tgt_iterator *tit;
4251 extract_unc_hostname(server->hostname, &tcp_host, &tcp_host_len);
4253 tit = dfs_cache_get_tgt_iterator(tl);
4259 /* Try to tree connect to all dfs targets */
4260 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
4261 const char *target = dfs_cache_get_tgt_name(tit);
4262 struct dfs_cache_tgt_list ntl = DFS_CACHE_TGT_LIST_INIT(ntl);
4266 share = prefix = NULL;
4268 /* Check if share matches with tcp ses */
4269 rc = dfs_cache_get_tgt_share(server->current_fullpath + 1, tit, &share, &prefix);
4271 cifs_dbg(VFS, "%s: failed to parse target share: %d\n", __func__, rc);
4275 rc = target_share_matches_server(server, tcp_host, tcp_host_len, share,
4279 if (!target_match) {
4284 if (ipc->need_reconnect) {
4285 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4286 rc = ops->tree_connect(xid, ipc->ses, tree, ipc, cifs_sb->local_nls);
4291 scnprintf(tree, MAX_TREE_SIZE, "\\%s", share);
4293 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4297 * If no dfs referrals were returned from link target, then just do a TREE_CONNECT
4298 * to it. Otherwise, cache the dfs referral and then mark current tcp ses for
4299 * reconnect so either the demultiplex thread or the echo worker will reconnect to
4300 * newly resolved target.
4302 if (dfs_cache_find(xid, tcon->ses, cifs_sb->local_nls, cifs_remap(cifs_sb), target,
4304 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4307 rc = dfs_cache_noreq_update_tgthint(server->current_fullpath + 1, tit);
4309 rc = cifs_update_super_prepath(cifs_sb, prefix);
4311 /* Target is another dfs share */
4312 rc = update_server_fullpath(server, cifs_sb, target);
4313 dfs_cache_free_tgts(tl);
4317 list_replace_init(&ntl.tl_list, &tl->tl_list);
4319 dfs_cache_free_tgts(&ntl);
4331 static int tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4332 struct cifs_sb_info *cifs_sb, char *tree, bool islink,
4333 struct dfs_cache_tgt_list *tl)
4337 struct TCP_Server_Info *server = tcon->ses->server;
4340 rc = __tree_connect_dfs_target(xid, tcon, cifs_sb, tree, islink, tl);
4341 if (!rc || rc != -EREMOTE)
4343 } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
4345 * If we couldn't tree connect to any targets from last referral path, then retry from
4346 * original referral path.
4348 if (rc && server->current_fullpath != server->origin_fullpath) {
4349 server->current_fullpath = server->origin_fullpath;
4350 cifs_ses_mark_for_reconnect(tcon->ses);
4353 dfs_cache_free_tgts(tl);
4357 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4360 struct TCP_Server_Info *server = tcon->ses->server;
4361 const struct smb_version_operations *ops = server->ops;
4362 struct super_block *sb = NULL;
4363 struct cifs_sb_info *cifs_sb;
4364 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
4366 struct dfs_info3_param ref = {0};
4368 tree = kzalloc(MAX_TREE_SIZE, GFP_KERNEL);
4373 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4374 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, nlsc);
4378 sb = cifs_get_tcp_super(server);
4381 cifs_dbg(VFS, "%s: could not find superblock: %d\n", __func__, rc);
4385 cifs_sb = CIFS_SB(sb);
4387 /* If it is not dfs or there was no cached dfs referral, then reconnect to same share */
4388 if (!server->current_fullpath ||
4389 dfs_cache_noreq_find(server->current_fullpath + 1, &ref, &tl)) {
4390 rc = ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, cifs_sb->local_nls);
4394 rc = tree_connect_dfs_target(xid, tcon, cifs_sb, tree, ref.server_type == DFS_TYPE_LINK,
4396 free_dfs_info_param(&ref);
4400 cifs_put_tcp_super(sb);
4405 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4407 const struct smb_version_operations *ops = tcon->ses->server->ops;
4409 return ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, nlsc);