Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: LGPL-2.1
0002 /*
0003  *
0004  *   Copyright (C) International Business Machines  Corp., 2002,2011
0005  *   Author(s): Steve French (sfrench@us.ibm.com)
0006  *
0007  */
0008 #include <linux/fs.h>
0009 #include <linux/net.h>
0010 #include <linux/string.h>
0011 #include <linux/sched/mm.h>
0012 #include <linux/sched/signal.h>
0013 #include <linux/list.h>
0014 #include <linux/wait.h>
0015 #include <linux/slab.h>
0016 #include <linux/pagemap.h>
0017 #include <linux/ctype.h>
0018 #include <linux/utsname.h>
0019 #include <linux/mempool.h>
0020 #include <linux/delay.h>
0021 #include <linux/completion.h>
0022 #include <linux/kthread.h>
0023 #include <linux/pagevec.h>
0024 #include <linux/freezer.h>
0025 #include <linux/namei.h>
0026 #include <linux/uuid.h>
0027 #include <linux/uaccess.h>
0028 #include <asm/processor.h>
0029 #include <linux/inet.h>
0030 #include <linux/module.h>
0031 #include <keys/user-type.h>
0032 #include <net/ipv6.h>
0033 #include <linux/parser.h>
0034 #include <linux/bvec.h>
0035 #include "cifspdu.h"
0036 #include "cifsglob.h"
0037 #include "cifsproto.h"
0038 #include "cifs_unicode.h"
0039 #include "cifs_debug.h"
0040 #include "cifs_fs_sb.h"
0041 #include "ntlmssp.h"
0042 #include "nterr.h"
0043 #include "rfc1002pdu.h"
0044 #include "fscache.h"
0045 #include "smb2proto.h"
0046 #include "smbdirect.h"
0047 #include "dns_resolve.h"
0048 #ifdef CONFIG_CIFS_DFS_UPCALL
0049 #include "dfs_cache.h"
0050 #endif
0051 #include "fs_context.h"
0052 #include "cifs_swn.h"
0053 
0054 extern mempool_t *cifs_req_poolp;
0055 extern bool disable_legacy_dialects;
0056 
0057 /* FIXME: should these be tunable? */
0058 #define TLINK_ERROR_EXPIRE  (1 * HZ)
0059 #define TLINK_IDLE_EXPIRE   (600 * HZ)
0060 
0061 /* Drop the connection to not overload the server */
0062 #define NUM_STATUS_IO_TIMEOUT   5
0063 
0064 struct mount_ctx {
0065     struct cifs_sb_info *cifs_sb;
0066     struct smb3_fs_context *fs_ctx;
0067     unsigned int xid;
0068     struct TCP_Server_Info *server;
0069     struct cifs_ses *ses;
0070     struct cifs_tcon *tcon;
0071 #ifdef CONFIG_CIFS_DFS_UPCALL
0072     struct cifs_ses *root_ses;
0073     uuid_t mount_id;
0074     char *origin_fullpath, *leaf_fullpath;
0075 #endif
0076 };
0077 
0078 static int ip_connect(struct TCP_Server_Info *server);
0079 static int generic_ip_connect(struct TCP_Server_Info *server);
0080 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
0081 static void cifs_prune_tlinks(struct work_struct *work);
0082 
0083 /*
0084  * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
0085  * get their ip addresses changed at some point.
0086  *
0087  * This should be called with server->srv_mutex held.
0088  */
0089 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
0090 {
0091     int rc;
0092     int len;
0093     char *unc, *ipaddr = NULL;
0094     time64_t expiry, now;
0095     unsigned long ttl = SMB_DNS_RESOLVE_INTERVAL_DEFAULT;
0096 
0097     if (!server->hostname)
0098         return -EINVAL;
0099 
0100     /* if server hostname isn't populated, there's nothing to do here */
0101     if (server->hostname[0] == '\0')
0102         return 0;
0103 
0104     len = strlen(server->hostname) + 3;
0105 
0106     unc = kmalloc(len, GFP_KERNEL);
0107     if (!unc) {
0108         cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
0109         return -ENOMEM;
0110     }
0111     scnprintf(unc, len, "\\\\%s", server->hostname);
0112 
0113     rc = dns_resolve_server_name_to_ip(unc, &ipaddr, &expiry);
0114     kfree(unc);
0115 
0116     if (rc < 0) {
0117         cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
0118              __func__, server->hostname, rc);
0119         goto requeue_resolve;
0120     }
0121 
0122     spin_lock(&server->srv_lock);
0123     rc = cifs_convert_address((struct sockaddr *)&server->dstaddr, ipaddr,
0124                   strlen(ipaddr));
0125     spin_unlock(&server->srv_lock);
0126     kfree(ipaddr);
0127 
0128     /* rc == 1 means success here */
0129     if (rc) {
0130         now = ktime_get_real_seconds();
0131         if (expiry && expiry > now)
0132             /*
0133              * To make sure we don't use the cached entry, retry 1s
0134              * after expiry.
0135              */
0136             ttl = max_t(unsigned long, expiry - now, SMB_DNS_RESOLVE_INTERVAL_MIN) + 1;
0137     }
0138     rc = !rc ? -1 : 0;
0139 
0140 requeue_resolve:
0141     cifs_dbg(FYI, "%s: next dns resolution scheduled for %lu seconds in the future\n",
0142          __func__, ttl);
0143     mod_delayed_work(cifsiod_wq, &server->resolve, (ttl * HZ));
0144 
0145     return rc;
0146 }
0147 
0148 static void smb2_query_server_interfaces(struct work_struct *work)
0149 {
0150     int rc;
0151     struct cifs_tcon *tcon = container_of(work,
0152                     struct cifs_tcon,
0153                     query_interfaces.work);
0154 
0155     /*
0156      * query server network interfaces, in case they change
0157      */
0158     rc = SMB3_request_interfaces(0, tcon);
0159     if (rc) {
0160         cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
0161                 __func__, rc);
0162     }
0163 
0164     queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
0165                (SMB_INTERFACE_POLL_INTERVAL * HZ));
0166 }
0167 
0168 static void cifs_resolve_server(struct work_struct *work)
0169 {
0170     int rc;
0171     struct TCP_Server_Info *server = container_of(work,
0172                     struct TCP_Server_Info, resolve.work);
0173 
0174     cifs_server_lock(server);
0175 
0176     /*
0177      * Resolve the hostname again to make sure that IP address is up-to-date.
0178      */
0179     rc = reconn_set_ipaddr_from_hostname(server);
0180     if (rc) {
0181         cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
0182                 __func__, rc);
0183     }
0184 
0185     cifs_server_unlock(server);
0186 }
0187 
0188 /*
0189  * Update the tcpStatus for the server.
0190  * This is used to signal the cifsd thread to call cifs_reconnect
0191  * ONLY cifsd thread should call cifs_reconnect. For any other
0192  * thread, use this function
0193  *
0194  * @server: the tcp ses for which reconnect is needed
0195  * @all_channels: if this needs to be done for all channels
0196  */
0197 void
0198 cifs_signal_cifsd_for_reconnect(struct TCP_Server_Info *server,
0199                 bool all_channels)
0200 {
0201     struct TCP_Server_Info *pserver;
0202     struct cifs_ses *ses;
0203     int i;
0204 
0205     /* If server is a channel, select the primary channel */
0206     pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
0207 
0208     spin_lock(&pserver->srv_lock);
0209     if (!all_channels) {
0210         pserver->tcpStatus = CifsNeedReconnect;
0211         spin_unlock(&pserver->srv_lock);
0212         return;
0213     }
0214     spin_unlock(&pserver->srv_lock);
0215 
0216     spin_lock(&cifs_tcp_ses_lock);
0217     list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
0218         spin_lock(&ses->chan_lock);
0219         for (i = 0; i < ses->chan_count; i++) {
0220             spin_lock(&ses->chans[i].server->srv_lock);
0221             ses->chans[i].server->tcpStatus = CifsNeedReconnect;
0222             spin_unlock(&ses->chans[i].server->srv_lock);
0223         }
0224         spin_unlock(&ses->chan_lock);
0225     }
0226     spin_unlock(&cifs_tcp_ses_lock);
0227 }
0228 
0229 /*
0230  * Mark all sessions and tcons for reconnect.
0231  * IMPORTANT: make sure that this gets called only from
0232  * cifsd thread. For any other thread, use
0233  * cifs_signal_cifsd_for_reconnect
0234  *
0235  * @server: the tcp ses for which reconnect is needed
0236  * @server needs to be previously set to CifsNeedReconnect.
0237  * @mark_smb_session: whether even sessions need to be marked
0238  */
0239 void
0240 cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server,
0241                       bool mark_smb_session)
0242 {
0243     struct TCP_Server_Info *pserver;
0244     struct cifs_ses *ses, *nses;
0245     struct cifs_tcon *tcon;
0246 
0247     /*
0248      * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
0249      * are not used until reconnected.
0250      */
0251     cifs_dbg(FYI, "%s: marking necessary sessions and tcons for reconnect\n", __func__);
0252 
0253     /* If server is a channel, select the primary channel */
0254     pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
0255 
0256 
0257     spin_lock(&cifs_tcp_ses_lock);
0258     list_for_each_entry_safe(ses, nses, &pserver->smb_ses_list, smb_ses_list) {
0259         /* check if iface is still active */
0260         if (!cifs_chan_is_iface_active(ses, server))
0261             cifs_chan_update_iface(ses, server);
0262 
0263         spin_lock(&ses->chan_lock);
0264         if (!mark_smb_session && cifs_chan_needs_reconnect(ses, server))
0265             goto next_session;
0266 
0267         if (mark_smb_session)
0268             CIFS_SET_ALL_CHANS_NEED_RECONNECT(ses);
0269         else
0270             cifs_chan_set_need_reconnect(ses, server);
0271 
0272         /* If all channels need reconnect, then tcon needs reconnect */
0273         if (!mark_smb_session && !CIFS_ALL_CHANS_NEED_RECONNECT(ses))
0274             goto next_session;
0275 
0276         ses->ses_status = SES_NEED_RECON;
0277 
0278         list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
0279             tcon->need_reconnect = true;
0280             tcon->status = TID_NEED_RECON;
0281         }
0282         if (ses->tcon_ipc)
0283             ses->tcon_ipc->need_reconnect = true;
0284 
0285 next_session:
0286         spin_unlock(&ses->chan_lock);
0287     }
0288     spin_unlock(&cifs_tcp_ses_lock);
0289 }
0290 
0291 static void
0292 cifs_abort_connection(struct TCP_Server_Info *server)
0293 {
0294     struct mid_q_entry *mid, *nmid;
0295     struct list_head retry_list;
0296 
0297     server->maxBuf = 0;
0298     server->max_read = 0;
0299 
0300     /* do not want to be sending data on a socket we are freeing */
0301     cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
0302     cifs_server_lock(server);
0303     if (server->ssocket) {
0304         cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
0305              server->ssocket->flags);
0306         kernel_sock_shutdown(server->ssocket, SHUT_WR);
0307         cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
0308              server->ssocket->flags);
0309         sock_release(server->ssocket);
0310         server->ssocket = NULL;
0311     }
0312     server->sequence_number = 0;
0313     server->session_estab = false;
0314     kfree(server->session_key.response);
0315     server->session_key.response = NULL;
0316     server->session_key.len = 0;
0317     server->lstrp = jiffies;
0318 
0319     /* mark submitted MIDs for retry and issue callback */
0320     INIT_LIST_HEAD(&retry_list);
0321     cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
0322     spin_lock(&server->mid_lock);
0323     list_for_each_entry_safe(mid, nmid, &server->pending_mid_q, qhead) {
0324         kref_get(&mid->refcount);
0325         if (mid->mid_state == MID_REQUEST_SUBMITTED)
0326             mid->mid_state = MID_RETRY_NEEDED;
0327         list_move(&mid->qhead, &retry_list);
0328         mid->mid_flags |= MID_DELETED;
0329     }
0330     spin_unlock(&server->mid_lock);
0331     cifs_server_unlock(server);
0332 
0333     cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
0334     list_for_each_entry_safe(mid, nmid, &retry_list, qhead) {
0335         list_del_init(&mid->qhead);
0336         mid->callback(mid);
0337         release_mid(mid);
0338     }
0339 
0340     if (cifs_rdma_enabled(server)) {
0341         cifs_server_lock(server);
0342         smbd_destroy(server);
0343         cifs_server_unlock(server);
0344     }
0345 }
0346 
0347 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
0348 {
0349     spin_lock(&server->srv_lock);
0350     server->nr_targets = num_targets;
0351     if (server->tcpStatus == CifsExiting) {
0352         /* the demux thread will exit normally next time through the loop */
0353         spin_unlock(&server->srv_lock);
0354         wake_up(&server->response_q);
0355         return false;
0356     }
0357 
0358     cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
0359     trace_smb3_reconnect(server->CurrentMid, server->conn_id,
0360                  server->hostname);
0361     server->tcpStatus = CifsNeedReconnect;
0362 
0363     spin_unlock(&server->srv_lock);
0364     return true;
0365 }
0366 
0367 /*
0368  * cifs tcp session reconnection
0369  *
0370  * mark tcp session as reconnecting so temporarily locked
0371  * mark all smb sessions as reconnecting for tcp session
0372  * reconnect tcp session
0373  * wake up waiters on reconnection? - (not needed currently)
0374  *
0375  * if mark_smb_session is passed as true, unconditionally mark
0376  * the smb session (and tcon) for reconnect as well. This value
0377  * doesn't really matter for non-multichannel scenario.
0378  *
0379  */
0380 static int __cifs_reconnect(struct TCP_Server_Info *server,
0381                 bool mark_smb_session)
0382 {
0383     int rc = 0;
0384 
0385     if (!cifs_tcp_ses_needs_reconnect(server, 1))
0386         return 0;
0387 
0388     cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
0389 
0390     cifs_abort_connection(server);
0391 
0392     do {
0393         try_to_freeze();
0394         cifs_server_lock(server);
0395 
0396         if (!cifs_swn_set_server_dstaddr(server)) {
0397             /* resolve the hostname again to make sure that IP address is up-to-date */
0398             rc = reconn_set_ipaddr_from_hostname(server);
0399             cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
0400         }
0401 
0402         if (cifs_rdma_enabled(server))
0403             rc = smbd_reconnect(server);
0404         else
0405             rc = generic_ip_connect(server);
0406         if (rc) {
0407             cifs_server_unlock(server);
0408             cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
0409             msleep(3000);
0410         } else {
0411             atomic_inc(&tcpSesReconnectCount);
0412             set_credits(server, 1);
0413             spin_lock(&server->srv_lock);
0414             if (server->tcpStatus != CifsExiting)
0415                 server->tcpStatus = CifsNeedNegotiate;
0416             spin_unlock(&server->srv_lock);
0417             cifs_swn_reset_server_dstaddr(server);
0418             cifs_server_unlock(server);
0419             mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
0420         }
0421     } while (server->tcpStatus == CifsNeedReconnect);
0422 
0423     spin_lock(&server->srv_lock);
0424     if (server->tcpStatus == CifsNeedNegotiate)
0425         mod_delayed_work(cifsiod_wq, &server->echo, 0);
0426     spin_unlock(&server->srv_lock);
0427 
0428     wake_up(&server->response_q);
0429     return rc;
0430 }
0431 
0432 #ifdef CONFIG_CIFS_DFS_UPCALL
0433 static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
0434 {
0435     int rc;
0436     char *hostname;
0437 
0438     if (!cifs_swn_set_server_dstaddr(server)) {
0439         if (server->hostname != target) {
0440             hostname = extract_hostname(target);
0441             if (!IS_ERR(hostname)) {
0442                 kfree(server->hostname);
0443                 server->hostname = hostname;
0444             } else {
0445                 cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
0446                      __func__, PTR_ERR(hostname));
0447                 cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
0448                      server->hostname);
0449             }
0450         }
0451         /* resolve the hostname again to make sure that IP address is up-to-date. */
0452         rc = reconn_set_ipaddr_from_hostname(server);
0453         cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
0454     }
0455     /* Reconnect the socket */
0456     if (cifs_rdma_enabled(server))
0457         rc = smbd_reconnect(server);
0458     else
0459         rc = generic_ip_connect(server);
0460 
0461     return rc;
0462 }
0463 
0464 static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
0465                      struct dfs_cache_tgt_iterator **target_hint)
0466 {
0467     int rc;
0468     struct dfs_cache_tgt_iterator *tit;
0469 
0470     *target_hint = NULL;
0471 
0472     /* If dfs target list is empty, then reconnect to last server */
0473     tit = dfs_cache_get_tgt_iterator(tl);
0474     if (!tit)
0475         return __reconnect_target_unlocked(server, server->hostname);
0476 
0477     /* Otherwise, try every dfs target in @tl */
0478     for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
0479         rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
0480         if (!rc) {
0481             *target_hint = tit;
0482             break;
0483         }
0484     }
0485     return rc;
0486 }
0487 
0488 static int reconnect_dfs_server(struct TCP_Server_Info *server)
0489 {
0490     int rc = 0;
0491     const char *refpath = server->current_fullpath + 1;
0492     struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
0493     struct dfs_cache_tgt_iterator *target_hint = NULL;
0494     int num_targets = 0;
0495 
0496     /*
0497      * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
0498      *
0499      * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
0500      * targets (server->nr_targets).  It's also possible that the cached referral was cleared
0501      * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
0502      * refreshing the referral, so, in this case, default it to 1.
0503      */
0504     if (!dfs_cache_noreq_find(refpath, NULL, &tl))
0505         num_targets = dfs_cache_get_nr_tgts(&tl);
0506     if (!num_targets)
0507         num_targets = 1;
0508 
0509     if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
0510         return 0;
0511 
0512     /*
0513      * Unconditionally mark all sessions & tcons for reconnect as we might be connecting to a
0514      * different server or share during failover.  It could be improved by adding some logic to
0515      * only do that in case it connects to a different server or share, though.
0516      */
0517     cifs_mark_tcp_ses_conns_for_reconnect(server, true);
0518 
0519     cifs_abort_connection(server);
0520 
0521     do {
0522         try_to_freeze();
0523         cifs_server_lock(server);
0524 
0525         rc = reconnect_target_unlocked(server, &tl, &target_hint);
0526         if (rc) {
0527             /* Failed to reconnect socket */
0528             cifs_server_unlock(server);
0529             cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
0530             msleep(3000);
0531             continue;
0532         }
0533         /*
0534          * Socket was created.  Update tcp session status to CifsNeedNegotiate so that a
0535          * process waiting for reconnect will know it needs to re-establish session and tcon
0536          * through the reconnected target server.
0537          */
0538         atomic_inc(&tcpSesReconnectCount);
0539         set_credits(server, 1);
0540         spin_lock(&server->srv_lock);
0541         if (server->tcpStatus != CifsExiting)
0542             server->tcpStatus = CifsNeedNegotiate;
0543         spin_unlock(&server->srv_lock);
0544         cifs_swn_reset_server_dstaddr(server);
0545         cifs_server_unlock(server);
0546         mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
0547     } while (server->tcpStatus == CifsNeedReconnect);
0548 
0549     if (target_hint)
0550         dfs_cache_noreq_update_tgthint(refpath, target_hint);
0551 
0552     dfs_cache_free_tgts(&tl);
0553 
0554     /* Need to set up echo worker again once connection has been established */
0555     spin_lock(&server->srv_lock);
0556     if (server->tcpStatus == CifsNeedNegotiate)
0557         mod_delayed_work(cifsiod_wq, &server->echo, 0);
0558     spin_unlock(&server->srv_lock);
0559 
0560     wake_up(&server->response_q);
0561     return rc;
0562 }
0563 
0564 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
0565 {
0566     /* If tcp session is not an dfs connection, then reconnect to last target server */
0567     spin_lock(&server->srv_lock);
0568     if (!server->is_dfs_conn) {
0569         spin_unlock(&server->srv_lock);
0570         return __cifs_reconnect(server, mark_smb_session);
0571     }
0572     spin_unlock(&server->srv_lock);
0573 
0574     mutex_lock(&server->refpath_lock);
0575     if (!server->origin_fullpath || !server->leaf_fullpath) {
0576         mutex_unlock(&server->refpath_lock);
0577         return __cifs_reconnect(server, mark_smb_session);
0578     }
0579     mutex_unlock(&server->refpath_lock);
0580 
0581     return reconnect_dfs_server(server);
0582 }
0583 #else
0584 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
0585 {
0586     return __cifs_reconnect(server, mark_smb_session);
0587 }
0588 #endif
0589 
0590 static void
0591 cifs_echo_request(struct work_struct *work)
0592 {
0593     int rc;
0594     struct TCP_Server_Info *server = container_of(work,
0595                     struct TCP_Server_Info, echo.work);
0596 
0597     /*
0598      * We cannot send an echo if it is disabled.
0599      * Also, no need to ping if we got a response recently.
0600      */
0601 
0602     if (server->tcpStatus == CifsNeedReconnect ||
0603         server->tcpStatus == CifsExiting ||
0604         server->tcpStatus == CifsNew ||
0605         (server->ops->can_echo && !server->ops->can_echo(server)) ||
0606         time_before(jiffies, server->lstrp + server->echo_interval - HZ))
0607         goto requeue_echo;
0608 
0609     rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
0610     if (rc)
0611         cifs_dbg(FYI, "Unable to send echo request to server: %s\n",
0612              server->hostname);
0613 
0614     /* Check witness registrations */
0615     cifs_swn_check();
0616 
0617 requeue_echo:
0618     queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
0619 }
0620 
0621 static bool
0622 allocate_buffers(struct TCP_Server_Info *server)
0623 {
0624     if (!server->bigbuf) {
0625         server->bigbuf = (char *)cifs_buf_get();
0626         if (!server->bigbuf) {
0627             cifs_server_dbg(VFS, "No memory for large SMB response\n");
0628             msleep(3000);
0629             /* retry will check if exiting */
0630             return false;
0631         }
0632     } else if (server->large_buf) {
0633         /* we are reusing a dirty large buf, clear its start */
0634         memset(server->bigbuf, 0, HEADER_SIZE(server));
0635     }
0636 
0637     if (!server->smallbuf) {
0638         server->smallbuf = (char *)cifs_small_buf_get();
0639         if (!server->smallbuf) {
0640             cifs_server_dbg(VFS, "No memory for SMB response\n");
0641             msleep(1000);
0642             /* retry will check if exiting */
0643             return false;
0644         }
0645         /* beginning of smb buffer is cleared in our buf_get */
0646     } else {
0647         /* if existing small buf clear beginning */
0648         memset(server->smallbuf, 0, HEADER_SIZE(server));
0649     }
0650 
0651     return true;
0652 }
0653 
0654 static bool
0655 server_unresponsive(struct TCP_Server_Info *server)
0656 {
0657     /*
0658      * We need to wait 3 echo intervals to make sure we handle such
0659      * situations right:
0660      * 1s  client sends a normal SMB request
0661      * 2s  client gets a response
0662      * 30s echo workqueue job pops, and decides we got a response recently
0663      *     and don't need to send another
0664      * ...
0665      * 65s kernel_recvmsg times out, and we see that we haven't gotten
0666      *     a response in >60s.
0667      */
0668     spin_lock(&server->srv_lock);
0669     if ((server->tcpStatus == CifsGood ||
0670         server->tcpStatus == CifsNeedNegotiate) &&
0671         (!server->ops->can_echo || server->ops->can_echo(server)) &&
0672         time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
0673         spin_unlock(&server->srv_lock);
0674         cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
0675              (3 * server->echo_interval) / HZ);
0676         cifs_reconnect(server, false);
0677         return true;
0678     }
0679     spin_unlock(&server->srv_lock);
0680 
0681     return false;
0682 }
0683 
0684 static inline bool
0685 zero_credits(struct TCP_Server_Info *server)
0686 {
0687     int val;
0688 
0689     spin_lock(&server->req_lock);
0690     val = server->credits + server->echo_credits + server->oplock_credits;
0691     if (server->in_flight == 0 && val == 0) {
0692         spin_unlock(&server->req_lock);
0693         return true;
0694     }
0695     spin_unlock(&server->req_lock);
0696     return false;
0697 }
0698 
0699 static int
0700 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
0701 {
0702     int length = 0;
0703     int total_read;
0704 
0705     for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
0706         try_to_freeze();
0707 
0708         /* reconnect if no credits and no requests in flight */
0709         if (zero_credits(server)) {
0710             cifs_reconnect(server, false);
0711             return -ECONNABORTED;
0712         }
0713 
0714         if (server_unresponsive(server))
0715             return -ECONNABORTED;
0716         if (cifs_rdma_enabled(server) && server->smbd_conn)
0717             length = smbd_recv(server->smbd_conn, smb_msg);
0718         else
0719             length = sock_recvmsg(server->ssocket, smb_msg, 0);
0720 
0721         spin_lock(&server->srv_lock);
0722         if (server->tcpStatus == CifsExiting) {
0723             spin_unlock(&server->srv_lock);
0724             return -ESHUTDOWN;
0725         }
0726 
0727         if (server->tcpStatus == CifsNeedReconnect) {
0728             spin_unlock(&server->srv_lock);
0729             cifs_reconnect(server, false);
0730             return -ECONNABORTED;
0731         }
0732         spin_unlock(&server->srv_lock);
0733 
0734         if (length == -ERESTARTSYS ||
0735             length == -EAGAIN ||
0736             length == -EINTR) {
0737             /*
0738              * Minimum sleep to prevent looping, allowing socket
0739              * to clear and app threads to set tcpStatus
0740              * CifsNeedReconnect if server hung.
0741              */
0742             usleep_range(1000, 2000);
0743             length = 0;
0744             continue;
0745         }
0746 
0747         if (length <= 0) {
0748             cifs_dbg(FYI, "Received no data or error: %d\n", length);
0749             cifs_reconnect(server, false);
0750             return -ECONNABORTED;
0751         }
0752     }
0753     return total_read;
0754 }
0755 
0756 int
0757 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
0758               unsigned int to_read)
0759 {
0760     struct msghdr smb_msg = {};
0761     struct kvec iov = {.iov_base = buf, .iov_len = to_read};
0762     iov_iter_kvec(&smb_msg.msg_iter, READ, &iov, 1, to_read);
0763 
0764     return cifs_readv_from_socket(server, &smb_msg);
0765 }
0766 
0767 ssize_t
0768 cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
0769 {
0770     struct msghdr smb_msg = {};
0771 
0772     /*
0773      *  iov_iter_discard already sets smb_msg.type and count and iov_offset
0774      *  and cifs_readv_from_socket sets msg_control and msg_controllen
0775      *  so little to initialize in struct msghdr
0776      */
0777     iov_iter_discard(&smb_msg.msg_iter, READ, to_read);
0778 
0779     return cifs_readv_from_socket(server, &smb_msg);
0780 }
0781 
0782 int
0783 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
0784     unsigned int page_offset, unsigned int to_read)
0785 {
0786     struct msghdr smb_msg = {};
0787     struct bio_vec bv = {
0788         .bv_page = page, .bv_len = to_read, .bv_offset = page_offset};
0789     iov_iter_bvec(&smb_msg.msg_iter, READ, &bv, 1, to_read);
0790     return cifs_readv_from_socket(server, &smb_msg);
0791 }
0792 
0793 static bool
0794 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
0795 {
0796     /*
0797      * The first byte big endian of the length field,
0798      * is actually not part of the length but the type
0799      * with the most common, zero, as regular data.
0800      */
0801     switch (type) {
0802     case RFC1002_SESSION_MESSAGE:
0803         /* Regular SMB response */
0804         return true;
0805     case RFC1002_SESSION_KEEP_ALIVE:
0806         cifs_dbg(FYI, "RFC 1002 session keep alive\n");
0807         break;
0808     case RFC1002_POSITIVE_SESSION_RESPONSE:
0809         cifs_dbg(FYI, "RFC 1002 positive session response\n");
0810         break;
0811     case RFC1002_NEGATIVE_SESSION_RESPONSE:
0812         /*
0813          * We get this from Windows 98 instead of an error on
0814          * SMB negprot response.
0815          */
0816         cifs_dbg(FYI, "RFC 1002 negative session response\n");
0817         /* give server a second to clean up */
0818         msleep(1000);
0819         /*
0820          * Always try 445 first on reconnect since we get NACK
0821          * on some if we ever connected to port 139 (the NACK
0822          * is since we do not begin with RFC1001 session
0823          * initialize frame).
0824          */
0825         cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
0826         cifs_reconnect(server, true);
0827         break;
0828     default:
0829         cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
0830         cifs_reconnect(server, true);
0831     }
0832 
0833     return false;
0834 }
0835 
0836 void
0837 dequeue_mid(struct mid_q_entry *mid, bool malformed)
0838 {
0839 #ifdef CONFIG_CIFS_STATS2
0840     mid->when_received = jiffies;
0841 #endif
0842     spin_lock(&mid->server->mid_lock);
0843     if (!malformed)
0844         mid->mid_state = MID_RESPONSE_RECEIVED;
0845     else
0846         mid->mid_state = MID_RESPONSE_MALFORMED;
0847     /*
0848      * Trying to handle/dequeue a mid after the send_recv()
0849      * function has finished processing it is a bug.
0850      */
0851     if (mid->mid_flags & MID_DELETED) {
0852         spin_unlock(&mid->server->mid_lock);
0853         pr_warn_once("trying to dequeue a deleted mid\n");
0854     } else {
0855         list_del_init(&mid->qhead);
0856         mid->mid_flags |= MID_DELETED;
0857         spin_unlock(&mid->server->mid_lock);
0858     }
0859 }
0860 
0861 static unsigned int
0862 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
0863 {
0864     struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
0865 
0866     /*
0867      * SMB1 does not use credits.
0868      */
0869     if (is_smb1(server))
0870         return 0;
0871 
0872     return le16_to_cpu(shdr->CreditRequest);
0873 }
0874 
0875 static void
0876 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
0877        char *buf, int malformed)
0878 {
0879     if (server->ops->check_trans2 &&
0880         server->ops->check_trans2(mid, server, buf, malformed))
0881         return;
0882     mid->credits_received = smb2_get_credits_from_hdr(buf, server);
0883     mid->resp_buf = buf;
0884     mid->large_buf = server->large_buf;
0885     /* Was previous buf put in mpx struct for multi-rsp? */
0886     if (!mid->multiRsp) {
0887         /* smb buffer will be freed by user thread */
0888         if (server->large_buf)
0889             server->bigbuf = NULL;
0890         else
0891             server->smallbuf = NULL;
0892     }
0893     dequeue_mid(mid, malformed);
0894 }
0895 
0896 int
0897 cifs_enable_signing(struct TCP_Server_Info *server, bool mnt_sign_required)
0898 {
0899     bool srv_sign_required = server->sec_mode & server->vals->signing_required;
0900     bool srv_sign_enabled = server->sec_mode & server->vals->signing_enabled;
0901     bool mnt_sign_enabled;
0902 
0903     /*
0904      * Is signing required by mnt options? If not then check
0905      * global_secflags to see if it is there.
0906      */
0907     if (!mnt_sign_required)
0908         mnt_sign_required = ((global_secflags & CIFSSEC_MUST_SIGN) ==
0909                         CIFSSEC_MUST_SIGN);
0910 
0911     /*
0912      * If signing is required then it's automatically enabled too,
0913      * otherwise, check to see if the secflags allow it.
0914      */
0915     mnt_sign_enabled = mnt_sign_required ? mnt_sign_required :
0916                 (global_secflags & CIFSSEC_MAY_SIGN);
0917 
0918     /* If server requires signing, does client allow it? */
0919     if (srv_sign_required) {
0920         if (!mnt_sign_enabled) {
0921             cifs_dbg(VFS, "Server requires signing, but it's disabled in SecurityFlags!\n");
0922             return -EOPNOTSUPP;
0923         }
0924         server->sign = true;
0925     }
0926 
0927     /* If client requires signing, does server allow it? */
0928     if (mnt_sign_required) {
0929         if (!srv_sign_enabled) {
0930             cifs_dbg(VFS, "Server does not support signing!\n");
0931             return -EOPNOTSUPP;
0932         }
0933         server->sign = true;
0934     }
0935 
0936     if (cifs_rdma_enabled(server) && server->sign)
0937         cifs_dbg(VFS, "Signing is enabled, and RDMA read/write will be disabled\n");
0938 
0939     return 0;
0940 }
0941 
0942 
0943 static void clean_demultiplex_info(struct TCP_Server_Info *server)
0944 {
0945     int length;
0946 
0947     /* take it off the list, if it's not already */
0948     spin_lock(&server->srv_lock);
0949     list_del_init(&server->tcp_ses_list);
0950     spin_unlock(&server->srv_lock);
0951 
0952     cancel_delayed_work_sync(&server->echo);
0953     cancel_delayed_work_sync(&server->resolve);
0954 
0955     spin_lock(&server->srv_lock);
0956     server->tcpStatus = CifsExiting;
0957     spin_unlock(&server->srv_lock);
0958     wake_up_all(&server->response_q);
0959 
0960     /* check if we have blocked requests that need to free */
0961     spin_lock(&server->req_lock);
0962     if (server->credits <= 0)
0963         server->credits = 1;
0964     spin_unlock(&server->req_lock);
0965     /*
0966      * Although there should not be any requests blocked on this queue it
0967      * can not hurt to be paranoid and try to wake up requests that may
0968      * haven been blocked when more than 50 at time were on the wire to the
0969      * same server - they now will see the session is in exit state and get
0970      * out of SendReceive.
0971      */
0972     wake_up_all(&server->request_q);
0973     /* give those requests time to exit */
0974     msleep(125);
0975     if (cifs_rdma_enabled(server))
0976         smbd_destroy(server);
0977     if (server->ssocket) {
0978         sock_release(server->ssocket);
0979         server->ssocket = NULL;
0980     }
0981 
0982     if (!list_empty(&server->pending_mid_q)) {
0983         struct list_head dispose_list;
0984         struct mid_q_entry *mid_entry;
0985         struct list_head *tmp, *tmp2;
0986 
0987         INIT_LIST_HEAD(&dispose_list);
0988         spin_lock(&server->mid_lock);
0989         list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
0990             mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
0991             cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
0992             kref_get(&mid_entry->refcount);
0993             mid_entry->mid_state = MID_SHUTDOWN;
0994             list_move(&mid_entry->qhead, &dispose_list);
0995             mid_entry->mid_flags |= MID_DELETED;
0996         }
0997         spin_unlock(&server->mid_lock);
0998 
0999         /* now walk dispose list and issue callbacks */
1000         list_for_each_safe(tmp, tmp2, &dispose_list) {
1001             mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
1002             cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
1003             list_del_init(&mid_entry->qhead);
1004             mid_entry->callback(mid_entry);
1005             release_mid(mid_entry);
1006         }
1007         /* 1/8th of sec is more than enough time for them to exit */
1008         msleep(125);
1009     }
1010 
1011     if (!list_empty(&server->pending_mid_q)) {
1012         /*
1013          * mpx threads have not exited yet give them at least the smb
1014          * send timeout time for long ops.
1015          *
1016          * Due to delays on oplock break requests, we need to wait at
1017          * least 45 seconds before giving up on a request getting a
1018          * response and going ahead and killing cifsd.
1019          */
1020         cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
1021         msleep(46000);
1022         /*
1023          * If threads still have not exited they are probably never
1024          * coming home not much else we can do but free the memory.
1025          */
1026     }
1027 
1028 #ifdef CONFIG_CIFS_DFS_UPCALL
1029     kfree(server->origin_fullpath);
1030     kfree(server->leaf_fullpath);
1031 #endif
1032     kfree(server);
1033 
1034     length = atomic_dec_return(&tcpSesAllocCount);
1035     if (length > 0)
1036         mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1037 }
1038 
1039 static int
1040 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1041 {
1042     int length;
1043     char *buf = server->smallbuf;
1044     unsigned int pdu_length = server->pdu_size;
1045 
1046     /* make sure this will fit in a large buffer */
1047     if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
1048         HEADER_PREAMBLE_SIZE(server)) {
1049         cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
1050         cifs_reconnect(server, true);
1051         return -ECONNABORTED;
1052     }
1053 
1054     /* switch to large buffer if too big for a small one */
1055     if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
1056         server->large_buf = true;
1057         memcpy(server->bigbuf, buf, server->total_read);
1058         buf = server->bigbuf;
1059     }
1060 
1061     /* now read the rest */
1062     length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
1063                        pdu_length - MID_HEADER_SIZE(server));
1064 
1065     if (length < 0)
1066         return length;
1067     server->total_read += length;
1068 
1069     dump_smb(buf, server->total_read);
1070 
1071     return cifs_handle_standard(server, mid);
1072 }
1073 
1074 int
1075 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1076 {
1077     char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1078     int rc;
1079 
1080     /*
1081      * We know that we received enough to get to the MID as we
1082      * checked the pdu_length earlier. Now check to see
1083      * if the rest of the header is OK.
1084      *
1085      * 48 bytes is enough to display the header and a little bit
1086      * into the payload for debugging purposes.
1087      */
1088     rc = server->ops->check_message(buf, server->total_read, server);
1089     if (rc)
1090         cifs_dump_mem("Bad SMB: ", buf,
1091             min_t(unsigned int, server->total_read, 48));
1092 
1093     if (server->ops->is_session_expired &&
1094         server->ops->is_session_expired(buf)) {
1095         cifs_reconnect(server, true);
1096         return -1;
1097     }
1098 
1099     if (server->ops->is_status_pending &&
1100         server->ops->is_status_pending(buf, server))
1101         return -1;
1102 
1103     if (!mid)
1104         return rc;
1105 
1106     handle_mid(mid, server, buf, rc);
1107     return 0;
1108 }
1109 
1110 static void
1111 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1112 {
1113     struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1114     int scredits, in_flight;
1115 
1116     /*
1117      * SMB1 does not use credits.
1118      */
1119     if (is_smb1(server))
1120         return;
1121 
1122     if (shdr->CreditRequest) {
1123         spin_lock(&server->req_lock);
1124         server->credits += le16_to_cpu(shdr->CreditRequest);
1125         scredits = server->credits;
1126         in_flight = server->in_flight;
1127         spin_unlock(&server->req_lock);
1128         wake_up(&server->request_q);
1129 
1130         trace_smb3_hdr_credits(server->CurrentMid,
1131                 server->conn_id, server->hostname, scredits,
1132                 le16_to_cpu(shdr->CreditRequest), in_flight);
1133         cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
1134                 __func__, le16_to_cpu(shdr->CreditRequest),
1135                 scredits);
1136     }
1137 }
1138 
1139 
1140 static int
1141 cifs_demultiplex_thread(void *p)
1142 {
1143     int i, num_mids, length;
1144     struct TCP_Server_Info *server = p;
1145     unsigned int pdu_length;
1146     unsigned int next_offset;
1147     char *buf = NULL;
1148     struct task_struct *task_to_wake = NULL;
1149     struct mid_q_entry *mids[MAX_COMPOUND];
1150     char *bufs[MAX_COMPOUND];
1151     unsigned int noreclaim_flag, num_io_timeout = 0;
1152 
1153     noreclaim_flag = memalloc_noreclaim_save();
1154     cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1155 
1156     length = atomic_inc_return(&tcpSesAllocCount);
1157     if (length > 1)
1158         mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1159 
1160     set_freezable();
1161     allow_kernel_signal(SIGKILL);
1162     while (server->tcpStatus != CifsExiting) {
1163         if (try_to_freeze())
1164             continue;
1165 
1166         if (!allocate_buffers(server))
1167             continue;
1168 
1169         server->large_buf = false;
1170         buf = server->smallbuf;
1171         pdu_length = 4; /* enough to get RFC1001 header */
1172 
1173         length = cifs_read_from_socket(server, buf, pdu_length);
1174         if (length < 0)
1175             continue;
1176 
1177         if (is_smb1(server))
1178             server->total_read = length;
1179         else
1180             server->total_read = 0;
1181 
1182         /*
1183          * The right amount was read from socket - 4 bytes,
1184          * so we can now interpret the length field.
1185          */
1186         pdu_length = get_rfc1002_length(buf);
1187 
1188         cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1189         if (!is_smb_response(server, buf[0]))
1190             continue;
1191 next_pdu:
1192         server->pdu_size = pdu_length;
1193 
1194         /* make sure we have enough to get to the MID */
1195         if (server->pdu_size < MID_HEADER_SIZE(server)) {
1196             cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1197                  server->pdu_size);
1198             cifs_reconnect(server, true);
1199             continue;
1200         }
1201 
1202         /* read down to the MID */
1203         length = cifs_read_from_socket(server,
1204                  buf + HEADER_PREAMBLE_SIZE(server),
1205                  MID_HEADER_SIZE(server));
1206         if (length < 0)
1207             continue;
1208         server->total_read += length;
1209 
1210         if (server->ops->next_header) {
1211             next_offset = server->ops->next_header(buf);
1212             if (next_offset)
1213                 server->pdu_size = next_offset;
1214         }
1215 
1216         memset(mids, 0, sizeof(mids));
1217         memset(bufs, 0, sizeof(bufs));
1218         num_mids = 0;
1219 
1220         if (server->ops->is_transform_hdr &&
1221             server->ops->receive_transform &&
1222             server->ops->is_transform_hdr(buf)) {
1223             length = server->ops->receive_transform(server,
1224                                 mids,
1225                                 bufs,
1226                                 &num_mids);
1227         } else {
1228             mids[0] = server->ops->find_mid(server, buf);
1229             bufs[0] = buf;
1230             num_mids = 1;
1231 
1232             if (!mids[0] || !mids[0]->receive)
1233                 length = standard_receive3(server, mids[0]);
1234             else
1235                 length = mids[0]->receive(server, mids[0]);
1236         }
1237 
1238         if (length < 0) {
1239             for (i = 0; i < num_mids; i++)
1240                 if (mids[i])
1241                     release_mid(mids[i]);
1242             continue;
1243         }
1244 
1245         if (server->ops->is_status_io_timeout &&
1246             server->ops->is_status_io_timeout(buf)) {
1247             num_io_timeout++;
1248             if (num_io_timeout > NUM_STATUS_IO_TIMEOUT) {
1249                 cifs_reconnect(server, false);
1250                 num_io_timeout = 0;
1251                 continue;
1252             }
1253         }
1254 
1255         server->lstrp = jiffies;
1256 
1257         for (i = 0; i < num_mids; i++) {
1258             if (mids[i] != NULL) {
1259                 mids[i]->resp_buf_size = server->pdu_size;
1260 
1261                 if (bufs[i] && server->ops->is_network_name_deleted)
1262                     server->ops->is_network_name_deleted(bufs[i],
1263                                     server);
1264 
1265                 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1266                     mids[i]->callback(mids[i]);
1267 
1268                 release_mid(mids[i]);
1269             } else if (server->ops->is_oplock_break &&
1270                    server->ops->is_oplock_break(bufs[i],
1271                                 server)) {
1272                 smb2_add_credits_from_hdr(bufs[i], server);
1273                 cifs_dbg(FYI, "Received oplock break\n");
1274             } else {
1275                 cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1276                         atomic_read(&mid_count));
1277                 cifs_dump_mem("Received Data is: ", bufs[i],
1278                           HEADER_SIZE(server));
1279                 smb2_add_credits_from_hdr(bufs[i], server);
1280 #ifdef CONFIG_CIFS_DEBUG2
1281                 if (server->ops->dump_detail)
1282                     server->ops->dump_detail(bufs[i],
1283                                  server);
1284                 cifs_dump_mids(server);
1285 #endif /* CIFS_DEBUG2 */
1286             }
1287         }
1288 
1289         if (pdu_length > server->pdu_size) {
1290             if (!allocate_buffers(server))
1291                 continue;
1292             pdu_length -= server->pdu_size;
1293             server->total_read = 0;
1294             server->large_buf = false;
1295             buf = server->smallbuf;
1296             goto next_pdu;
1297         }
1298     } /* end while !EXITING */
1299 
1300     /* buffer usually freed in free_mid - need to free it here on exit */
1301     cifs_buf_release(server->bigbuf);
1302     if (server->smallbuf) /* no sense logging a debug message if NULL */
1303         cifs_small_buf_release(server->smallbuf);
1304 
1305     task_to_wake = xchg(&server->tsk, NULL);
1306     clean_demultiplex_info(server);
1307 
1308     /* if server->tsk was NULL then wait for a signal before exiting */
1309     if (!task_to_wake) {
1310         set_current_state(TASK_INTERRUPTIBLE);
1311         while (!signal_pending(current)) {
1312             schedule();
1313             set_current_state(TASK_INTERRUPTIBLE);
1314         }
1315         set_current_state(TASK_RUNNING);
1316     }
1317 
1318     memalloc_noreclaim_restore(noreclaim_flag);
1319     module_put_and_kthread_exit(0);
1320 }
1321 
1322 /*
1323  * Returns true if srcaddr isn't specified and rhs isn't specified, or
1324  * if srcaddr is specified and matches the IP address of the rhs argument
1325  */
1326 bool
1327 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1328 {
1329     switch (srcaddr->sa_family) {
1330     case AF_UNSPEC:
1331         return (rhs->sa_family == AF_UNSPEC);
1332     case AF_INET: {
1333         struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1334         struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1335         return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1336     }
1337     case AF_INET6: {
1338         struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1339         struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1340         return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
1341     }
1342     default:
1343         WARN_ON(1);
1344         return false; /* don't expect to be here */
1345     }
1346 }
1347 
1348 /*
1349  * If no port is specified in addr structure, we try to match with 445 port
1350  * and if it fails - with 139 ports. It should be called only if address
1351  * families of server and addr are equal.
1352  */
1353 static bool
1354 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1355 {
1356     __be16 port, *sport;
1357 
1358     /* SMBDirect manages its own ports, don't match it here */
1359     if (server->rdma)
1360         return true;
1361 
1362     switch (addr->sa_family) {
1363     case AF_INET:
1364         sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1365         port = ((struct sockaddr_in *) addr)->sin_port;
1366         break;
1367     case AF_INET6:
1368         sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1369         port = ((struct sockaddr_in6 *) addr)->sin6_port;
1370         break;
1371     default:
1372         WARN_ON(1);
1373         return false;
1374     }
1375 
1376     if (!port) {
1377         port = htons(CIFS_PORT);
1378         if (port == *sport)
1379             return true;
1380 
1381         port = htons(RFC1001_PORT);
1382     }
1383 
1384     return port == *sport;
1385 }
1386 
1387 static bool
1388 match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
1389           struct sockaddr *srcaddr)
1390 {
1391     switch (addr->sa_family) {
1392     case AF_INET: {
1393         struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
1394         struct sockaddr_in *srv_addr4 =
1395                     (struct sockaddr_in *)&server->dstaddr;
1396 
1397         if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
1398             return false;
1399         break;
1400     }
1401     case AF_INET6: {
1402         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
1403         struct sockaddr_in6 *srv_addr6 =
1404                     (struct sockaddr_in6 *)&server->dstaddr;
1405 
1406         if (!ipv6_addr_equal(&addr6->sin6_addr,
1407                      &srv_addr6->sin6_addr))
1408             return false;
1409         if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
1410             return false;
1411         break;
1412     }
1413     default:
1414         WARN_ON(1);
1415         return false; /* don't expect to be here */
1416     }
1417 
1418     if (!cifs_match_ipaddr(srcaddr, (struct sockaddr *)&server->srcaddr))
1419         return false;
1420 
1421     return true;
1422 }
1423 
1424 static bool
1425 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1426 {
1427     /*
1428      * The select_sectype function should either return the ctx->sectype
1429      * that was specified, or "Unspecified" if that sectype was not
1430      * compatible with the given NEGOTIATE request.
1431      */
1432     if (server->ops->select_sectype(server, ctx->sectype)
1433          == Unspecified)
1434         return false;
1435 
1436     /*
1437      * Now check if signing mode is acceptable. No need to check
1438      * global_secflags at this point since if MUST_SIGN is set then
1439      * the server->sign had better be too.
1440      */
1441     if (ctx->sign && !server->sign)
1442         return false;
1443 
1444     return true;
1445 }
1446 
1447 /* this function must be called with srv_lock held */
1448 static int match_server(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1449 {
1450     struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1451 
1452     if (ctx->nosharesock)
1453         return 0;
1454 
1455     /* this server does not share socket */
1456     if (server->nosharesock)
1457         return 0;
1458 
1459     /* If multidialect negotiation see if existing sessions match one */
1460     if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1461         if (server->vals->protocol_id < SMB30_PROT_ID)
1462             return 0;
1463     } else if (strcmp(ctx->vals->version_string,
1464            SMBDEFAULT_VERSION_STRING) == 0) {
1465         if (server->vals->protocol_id < SMB21_PROT_ID)
1466             return 0;
1467     } else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1468         return 0;
1469 
1470     if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1471         return 0;
1472 
1473     if (strcasecmp(server->hostname, ctx->server_hostname))
1474         return 0;
1475 
1476     if (!match_address(server, addr,
1477                (struct sockaddr *)&ctx->srcaddr))
1478         return 0;
1479 
1480     if (!match_port(server, addr))
1481         return 0;
1482 
1483     if (!match_security(server, ctx))
1484         return 0;
1485 
1486     if (server->echo_interval != ctx->echo_interval * HZ)
1487         return 0;
1488 
1489     if (server->rdma != ctx->rdma)
1490         return 0;
1491 
1492     if (server->ignore_signature != ctx->ignore_signature)
1493         return 0;
1494 
1495     if (server->min_offload != ctx->min_offload)
1496         return 0;
1497 
1498     return 1;
1499 }
1500 
1501 struct TCP_Server_Info *
1502 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1503 {
1504     struct TCP_Server_Info *server;
1505 
1506     spin_lock(&cifs_tcp_ses_lock);
1507     list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1508         spin_lock(&server->srv_lock);
1509 #ifdef CONFIG_CIFS_DFS_UPCALL
1510         /*
1511          * DFS failover implementation in cifs_reconnect() requires unique tcp sessions for
1512          * DFS connections to do failover properly, so avoid sharing them with regular
1513          * shares or even links that may connect to same server but having completely
1514          * different failover targets.
1515          */
1516         if (server->is_dfs_conn) {
1517             spin_unlock(&server->srv_lock);
1518             continue;
1519         }
1520 #endif
1521         /*
1522          * Skip ses channels since they're only handled in lower layers
1523          * (e.g. cifs_send_recv).
1524          */
1525         if (CIFS_SERVER_IS_CHAN(server) || !match_server(server, ctx)) {
1526             spin_unlock(&server->srv_lock);
1527             continue;
1528         }
1529         spin_unlock(&server->srv_lock);
1530 
1531         ++server->srv_count;
1532         spin_unlock(&cifs_tcp_ses_lock);
1533         cifs_dbg(FYI, "Existing tcp session with server found\n");
1534         return server;
1535     }
1536     spin_unlock(&cifs_tcp_ses_lock);
1537     return NULL;
1538 }
1539 
1540 void
1541 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1542 {
1543     struct task_struct *task;
1544 
1545     spin_lock(&cifs_tcp_ses_lock);
1546     if (--server->srv_count > 0) {
1547         spin_unlock(&cifs_tcp_ses_lock);
1548         return;
1549     }
1550 
1551     /* srv_count can never go negative */
1552     WARN_ON(server->srv_count < 0);
1553 
1554     put_net(cifs_net_ns(server));
1555 
1556     list_del_init(&server->tcp_ses_list);
1557     spin_unlock(&cifs_tcp_ses_lock);
1558 
1559     /* For secondary channels, we pick up ref-count on the primary server */
1560     if (CIFS_SERVER_IS_CHAN(server))
1561         cifs_put_tcp_session(server->primary_server, from_reconnect);
1562 
1563     cancel_delayed_work_sync(&server->echo);
1564     cancel_delayed_work_sync(&server->resolve);
1565 
1566     if (from_reconnect)
1567         /*
1568          * Avoid deadlock here: reconnect work calls
1569          * cifs_put_tcp_session() at its end. Need to be sure
1570          * that reconnect work does nothing with server pointer after
1571          * that step.
1572          */
1573         cancel_delayed_work(&server->reconnect);
1574     else
1575         cancel_delayed_work_sync(&server->reconnect);
1576 
1577     spin_lock(&server->srv_lock);
1578     server->tcpStatus = CifsExiting;
1579     spin_unlock(&server->srv_lock);
1580 
1581     cifs_crypto_secmech_release(server);
1582 
1583     kfree(server->session_key.response);
1584     server->session_key.response = NULL;
1585     server->session_key.len = 0;
1586     kfree(server->hostname);
1587 
1588     task = xchg(&server->tsk, NULL);
1589     if (task)
1590         send_sig(SIGKILL, task, 1);
1591 }
1592 
1593 struct TCP_Server_Info *
1594 cifs_get_tcp_session(struct smb3_fs_context *ctx,
1595              struct TCP_Server_Info *primary_server)
1596 {
1597     struct TCP_Server_Info *tcp_ses = NULL;
1598     int rc;
1599 
1600     cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1601 
1602     /* see if we already have a matching tcp_ses */
1603     tcp_ses = cifs_find_tcp_session(ctx);
1604     if (tcp_ses)
1605         return tcp_ses;
1606 
1607     tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1608     if (!tcp_ses) {
1609         rc = -ENOMEM;
1610         goto out_err;
1611     }
1612 
1613     tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1614     if (!tcp_ses->hostname) {
1615         rc = -ENOMEM;
1616         goto out_err;
1617     }
1618 
1619     if (ctx->nosharesock)
1620         tcp_ses->nosharesock = true;
1621 
1622     tcp_ses->ops = ctx->ops;
1623     tcp_ses->vals = ctx->vals;
1624     cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1625 
1626     tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1627     tcp_ses->noblockcnt = ctx->rootfs;
1628     tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1629     tcp_ses->noautotune = ctx->noautotune;
1630     tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1631     tcp_ses->rdma = ctx->rdma;
1632     tcp_ses->in_flight = 0;
1633     tcp_ses->max_in_flight = 0;
1634     tcp_ses->credits = 1;
1635     if (primary_server) {
1636         spin_lock(&cifs_tcp_ses_lock);
1637         ++primary_server->srv_count;
1638         spin_unlock(&cifs_tcp_ses_lock);
1639         tcp_ses->primary_server = primary_server;
1640     }
1641     init_waitqueue_head(&tcp_ses->response_q);
1642     init_waitqueue_head(&tcp_ses->request_q);
1643     INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1644     mutex_init(&tcp_ses->_srv_mutex);
1645     memcpy(tcp_ses->workstation_RFC1001_name,
1646         ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1647     memcpy(tcp_ses->server_RFC1001_name,
1648         ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1649     tcp_ses->session_estab = false;
1650     tcp_ses->sequence_number = 0;
1651     tcp_ses->reconnect_instance = 1;
1652     tcp_ses->lstrp = jiffies;
1653     tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1654     spin_lock_init(&tcp_ses->req_lock);
1655     spin_lock_init(&tcp_ses->srv_lock);
1656     spin_lock_init(&tcp_ses->mid_lock);
1657     INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1658     INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1659     INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1660     INIT_DELAYED_WORK(&tcp_ses->resolve, cifs_resolve_server);
1661     INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1662     mutex_init(&tcp_ses->reconnect_mutex);
1663 #ifdef CONFIG_CIFS_DFS_UPCALL
1664     mutex_init(&tcp_ses->refpath_lock);
1665 #endif
1666     memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1667            sizeof(tcp_ses->srcaddr));
1668     memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1669         sizeof(tcp_ses->dstaddr));
1670     if (ctx->use_client_guid)
1671         memcpy(tcp_ses->client_guid, ctx->client_guid,
1672                SMB2_CLIENT_GUID_SIZE);
1673     else
1674         generate_random_uuid(tcp_ses->client_guid);
1675     /*
1676      * at this point we are the only ones with the pointer
1677      * to the struct since the kernel thread not created yet
1678      * no need to spinlock this init of tcpStatus or srv_count
1679      */
1680     tcp_ses->tcpStatus = CifsNew;
1681     ++tcp_ses->srv_count;
1682 
1683     if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1684         ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1685         tcp_ses->echo_interval = ctx->echo_interval * HZ;
1686     else
1687         tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1688     if (tcp_ses->rdma) {
1689 #ifndef CONFIG_CIFS_SMB_DIRECT
1690         cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1691         rc = -ENOENT;
1692         goto out_err_crypto_release;
1693 #endif
1694         tcp_ses->smbd_conn = smbd_get_connection(
1695             tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1696         if (tcp_ses->smbd_conn) {
1697             cifs_dbg(VFS, "RDMA transport established\n");
1698             rc = 0;
1699             goto smbd_connected;
1700         } else {
1701             rc = -ENOENT;
1702             goto out_err_crypto_release;
1703         }
1704     }
1705     rc = ip_connect(tcp_ses);
1706     if (rc < 0) {
1707         cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1708         goto out_err_crypto_release;
1709     }
1710 smbd_connected:
1711     /*
1712      * since we're in a cifs function already, we know that
1713      * this will succeed. No need for try_module_get().
1714      */
1715     __module_get(THIS_MODULE);
1716     tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1717                   tcp_ses, "cifsd");
1718     if (IS_ERR(tcp_ses->tsk)) {
1719         rc = PTR_ERR(tcp_ses->tsk);
1720         cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1721         module_put(THIS_MODULE);
1722         goto out_err_crypto_release;
1723     }
1724     tcp_ses->min_offload = ctx->min_offload;
1725     /*
1726      * at this point we are the only ones with the pointer
1727      * to the struct since the kernel thread not created yet
1728      * no need to spinlock this update of tcpStatus
1729      */
1730     spin_lock(&tcp_ses->srv_lock);
1731     tcp_ses->tcpStatus = CifsNeedNegotiate;
1732     spin_unlock(&tcp_ses->srv_lock);
1733 
1734     if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1735         tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1736     else
1737         tcp_ses->max_credits = ctx->max_credits;
1738 
1739     tcp_ses->nr_targets = 1;
1740     tcp_ses->ignore_signature = ctx->ignore_signature;
1741     /* thread spawned, put it on the list */
1742     spin_lock(&cifs_tcp_ses_lock);
1743     list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1744     spin_unlock(&cifs_tcp_ses_lock);
1745 
1746     /* queue echo request delayed work */
1747     queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1748 
1749     /* queue dns resolution delayed work */
1750     cifs_dbg(FYI, "%s: next dns resolution scheduled for %d seconds in the future\n",
1751          __func__, SMB_DNS_RESOLVE_INTERVAL_DEFAULT);
1752 
1753     queue_delayed_work(cifsiod_wq, &tcp_ses->resolve, (SMB_DNS_RESOLVE_INTERVAL_DEFAULT * HZ));
1754 
1755     return tcp_ses;
1756 
1757 out_err_crypto_release:
1758     cifs_crypto_secmech_release(tcp_ses);
1759 
1760     put_net(cifs_net_ns(tcp_ses));
1761 
1762 out_err:
1763     if (tcp_ses) {
1764         if (CIFS_SERVER_IS_CHAN(tcp_ses))
1765             cifs_put_tcp_session(tcp_ses->primary_server, false);
1766         kfree(tcp_ses->hostname);
1767         if (tcp_ses->ssocket)
1768             sock_release(tcp_ses->ssocket);
1769         kfree(tcp_ses);
1770     }
1771     return ERR_PTR(rc);
1772 }
1773 
1774 /* this function must be called with ses_lock held */
1775 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1776 {
1777     if (ctx->sectype != Unspecified &&
1778         ctx->sectype != ses->sectype)
1779         return 0;
1780 
1781     /*
1782      * If an existing session is limited to less channels than
1783      * requested, it should not be reused
1784      */
1785     spin_lock(&ses->chan_lock);
1786     if (ses->chan_max < ctx->max_channels) {
1787         spin_unlock(&ses->chan_lock);
1788         return 0;
1789     }
1790     spin_unlock(&ses->chan_lock);
1791 
1792     switch (ses->sectype) {
1793     case Kerberos:
1794         if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1795             return 0;
1796         break;
1797     default:
1798         /* NULL username means anonymous session */
1799         if (ses->user_name == NULL) {
1800             if (!ctx->nullauth)
1801                 return 0;
1802             break;
1803         }
1804 
1805         /* anything else takes username/password */
1806         if (strncmp(ses->user_name,
1807                 ctx->username ? ctx->username : "",
1808                 CIFS_MAX_USERNAME_LEN))
1809             return 0;
1810         if ((ctx->username && strlen(ctx->username) != 0) &&
1811             ses->password != NULL &&
1812             strncmp(ses->password,
1813                 ctx->password ? ctx->password : "",
1814                 CIFS_MAX_PASSWORD_LEN))
1815             return 0;
1816     }
1817     return 1;
1818 }
1819 
1820 /**
1821  * cifs_setup_ipc - helper to setup the IPC tcon for the session
1822  * @ses: smb session to issue the request on
1823  * @ctx: the superblock configuration context to use for building the
1824  *       new tree connection for the IPC (interprocess communication RPC)
1825  *
1826  * A new IPC connection is made and stored in the session
1827  * tcon_ipc. The IPC tcon has the same lifetime as the session.
1828  */
1829 static int
1830 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1831 {
1832     int rc = 0, xid;
1833     struct cifs_tcon *tcon;
1834     char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1835     bool seal = false;
1836     struct TCP_Server_Info *server = ses->server;
1837 
1838     /*
1839      * If the mount request that resulted in the creation of the
1840      * session requires encryption, force IPC to be encrypted too.
1841      */
1842     if (ctx->seal) {
1843         if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1844             seal = true;
1845         else {
1846             cifs_server_dbg(VFS,
1847                  "IPC: server doesn't support encryption\n");
1848             return -EOPNOTSUPP;
1849         }
1850     }
1851 
1852     tcon = tconInfoAlloc();
1853     if (tcon == NULL)
1854         return -ENOMEM;
1855 
1856     scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1857 
1858     xid = get_xid();
1859     tcon->ses = ses;
1860     tcon->ipc = true;
1861     tcon->seal = seal;
1862     rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1863     free_xid(xid);
1864 
1865     if (rc) {
1866         cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1867         tconInfoFree(tcon);
1868         goto out;
1869     }
1870 
1871     cifs_dbg(FYI, "IPC tcon rc=%d ipc tid=0x%x\n", rc, tcon->tid);
1872 
1873     ses->tcon_ipc = tcon;
1874 out:
1875     return rc;
1876 }
1877 
1878 /**
1879  * cifs_free_ipc - helper to release the session IPC tcon
1880  * @ses: smb session to unmount the IPC from
1881  *
1882  * Needs to be called everytime a session is destroyed.
1883  *
1884  * On session close, the IPC is closed and the server must release all tcons of the session.
1885  * No need to send a tree disconnect here.
1886  *
1887  * Besides, it will make the server to not close durable and resilient files on session close, as
1888  * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1889  */
1890 static int
1891 cifs_free_ipc(struct cifs_ses *ses)
1892 {
1893     struct cifs_tcon *tcon = ses->tcon_ipc;
1894 
1895     if (tcon == NULL)
1896         return 0;
1897 
1898     tconInfoFree(tcon);
1899     ses->tcon_ipc = NULL;
1900     return 0;
1901 }
1902 
1903 static struct cifs_ses *
1904 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1905 {
1906     struct cifs_ses *ses;
1907 
1908     spin_lock(&cifs_tcp_ses_lock);
1909     list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1910         spin_lock(&ses->ses_lock);
1911         if (ses->ses_status == SES_EXITING) {
1912             spin_unlock(&ses->ses_lock);
1913             continue;
1914         }
1915         if (!match_session(ses, ctx)) {
1916             spin_unlock(&ses->ses_lock);
1917             continue;
1918         }
1919         spin_unlock(&ses->ses_lock);
1920 
1921         ++ses->ses_count;
1922         spin_unlock(&cifs_tcp_ses_lock);
1923         return ses;
1924     }
1925     spin_unlock(&cifs_tcp_ses_lock);
1926     return NULL;
1927 }
1928 
1929 void cifs_put_smb_ses(struct cifs_ses *ses)
1930 {
1931     unsigned int rc, xid;
1932     unsigned int chan_count;
1933     struct TCP_Server_Info *server = ses->server;
1934 
1935     spin_lock(&ses->ses_lock);
1936     if (ses->ses_status == SES_EXITING) {
1937         spin_unlock(&ses->ses_lock);
1938         return;
1939     }
1940     spin_unlock(&ses->ses_lock);
1941 
1942     cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1943     cifs_dbg(FYI, "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->treeName : "NONE");
1944 
1945     spin_lock(&cifs_tcp_ses_lock);
1946     if (--ses->ses_count > 0) {
1947         spin_unlock(&cifs_tcp_ses_lock);
1948         return;
1949     }
1950     spin_unlock(&cifs_tcp_ses_lock);
1951 
1952     /* ses_count can never go negative */
1953     WARN_ON(ses->ses_count < 0);
1954 
1955     if (ses->ses_status == SES_GOOD)
1956         ses->ses_status = SES_EXITING;
1957 
1958     cifs_free_ipc(ses);
1959 
1960     if (ses->ses_status == SES_EXITING && server->ops->logoff) {
1961         xid = get_xid();
1962         rc = server->ops->logoff(xid, ses);
1963         if (rc)
1964             cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
1965                 __func__, rc);
1966         _free_xid(xid);
1967     }
1968 
1969     spin_lock(&cifs_tcp_ses_lock);
1970     list_del_init(&ses->smb_ses_list);
1971     spin_unlock(&cifs_tcp_ses_lock);
1972 
1973     chan_count = ses->chan_count;
1974 
1975     /* close any extra channels */
1976     if (chan_count > 1) {
1977         int i;
1978 
1979         for (i = 1; i < chan_count; i++) {
1980             if (ses->chans[i].iface) {
1981                 kref_put(&ses->chans[i].iface->refcount, release_iface);
1982                 ses->chans[i].iface = NULL;
1983             }
1984             cifs_put_tcp_session(ses->chans[i].server, 0);
1985             ses->chans[i].server = NULL;
1986         }
1987     }
1988 
1989     sesInfoFree(ses);
1990     cifs_put_tcp_session(server, 0);
1991 }
1992 
1993 #ifdef CONFIG_KEYS
1994 
1995 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
1996 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
1997 
1998 /* Populate username and pw fields from keyring if possible */
1999 static int
2000 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
2001 {
2002     int rc = 0;
2003     int is_domain = 0;
2004     const char *delim, *payload;
2005     char *desc;
2006     ssize_t len;
2007     struct key *key;
2008     struct TCP_Server_Info *server = ses->server;
2009     struct sockaddr_in *sa;
2010     struct sockaddr_in6 *sa6;
2011     const struct user_key_payload *upayload;
2012 
2013     desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2014     if (!desc)
2015         return -ENOMEM;
2016 
2017     /* try to find an address key first */
2018     switch (server->dstaddr.ss_family) {
2019     case AF_INET:
2020         sa = (struct sockaddr_in *)&server->dstaddr;
2021         sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2022         break;
2023     case AF_INET6:
2024         sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2025         sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2026         break;
2027     default:
2028         cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2029              server->dstaddr.ss_family);
2030         rc = -EINVAL;
2031         goto out_err;
2032     }
2033 
2034     cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2035     key = request_key(&key_type_logon, desc, "");
2036     if (IS_ERR(key)) {
2037         if (!ses->domainName) {
2038             cifs_dbg(FYI, "domainName is NULL\n");
2039             rc = PTR_ERR(key);
2040             goto out_err;
2041         }
2042 
2043         /* didn't work, try to find a domain key */
2044         sprintf(desc, "cifs:d:%s", ses->domainName);
2045         cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2046         key = request_key(&key_type_logon, desc, "");
2047         if (IS_ERR(key)) {
2048             rc = PTR_ERR(key);
2049             goto out_err;
2050         }
2051         is_domain = 1;
2052     }
2053 
2054     down_read(&key->sem);
2055     upayload = user_key_payload_locked(key);
2056     if (IS_ERR_OR_NULL(upayload)) {
2057         rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2058         goto out_key_put;
2059     }
2060 
2061     /* find first : in payload */
2062     payload = upayload->data;
2063     delim = strnchr(payload, upayload->datalen, ':');
2064     cifs_dbg(FYI, "payload=%s\n", payload);
2065     if (!delim) {
2066         cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2067              upayload->datalen);
2068         rc = -EINVAL;
2069         goto out_key_put;
2070     }
2071 
2072     len = delim - payload;
2073     if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2074         cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2075              len);
2076         rc = -EINVAL;
2077         goto out_key_put;
2078     }
2079 
2080     ctx->username = kstrndup(payload, len, GFP_KERNEL);
2081     if (!ctx->username) {
2082         cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2083              len);
2084         rc = -ENOMEM;
2085         goto out_key_put;
2086     }
2087     cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
2088 
2089     len = key->datalen - (len + 1);
2090     if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2091         cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2092         rc = -EINVAL;
2093         kfree(ctx->username);
2094         ctx->username = NULL;
2095         goto out_key_put;
2096     }
2097 
2098     ++delim;
2099     ctx->password = kstrndup(delim, len, GFP_KERNEL);
2100     if (!ctx->password) {
2101         cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2102              len);
2103         rc = -ENOMEM;
2104         kfree(ctx->username);
2105         ctx->username = NULL;
2106         goto out_key_put;
2107     }
2108 
2109     /*
2110      * If we have a domain key then we must set the domainName in the
2111      * for the request.
2112      */
2113     if (is_domain && ses->domainName) {
2114         ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2115         if (!ctx->domainname) {
2116             cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
2117                  len);
2118             rc = -ENOMEM;
2119             kfree(ctx->username);
2120             ctx->username = NULL;
2121             kfree_sensitive(ctx->password);
2122             ctx->password = NULL;
2123             goto out_key_put;
2124         }
2125     }
2126 
2127     strscpy(ctx->workstation_name, ses->workstation_name, sizeof(ctx->workstation_name));
2128 
2129 out_key_put:
2130     up_read(&key->sem);
2131     key_put(key);
2132 out_err:
2133     kfree(desc);
2134     cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2135     return rc;
2136 }
2137 #else /* ! CONFIG_KEYS */
2138 static inline int
2139 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2140            struct cifs_ses *ses __attribute__((unused)))
2141 {
2142     return -ENOSYS;
2143 }
2144 #endif /* CONFIG_KEYS */
2145 
2146 /**
2147  * cifs_get_smb_ses - get a session matching @ctx data from @server
2148  * @server: server to setup the session to
2149  * @ctx: superblock configuration context to use to setup the session
2150  *
2151  * This function assumes it is being called from cifs_mount() where we
2152  * already got a server reference (server refcount +1). See
2153  * cifs_get_tcon() for refcount explanations.
2154  */
2155 struct cifs_ses *
2156 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2157 {
2158     int rc = -ENOMEM;
2159     unsigned int xid;
2160     struct cifs_ses *ses;
2161     struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2162     struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2163 
2164     xid = get_xid();
2165 
2166     ses = cifs_find_smb_ses(server, ctx);
2167     if (ses) {
2168         cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2169              ses->ses_status);
2170 
2171         spin_lock(&ses->chan_lock);
2172         if (cifs_chan_needs_reconnect(ses, server)) {
2173             spin_unlock(&ses->chan_lock);
2174             cifs_dbg(FYI, "Session needs reconnect\n");
2175 
2176             mutex_lock(&ses->session_mutex);
2177             rc = cifs_negotiate_protocol(xid, ses, server);
2178             if (rc) {
2179                 mutex_unlock(&ses->session_mutex);
2180                 /* problem -- put our ses reference */
2181                 cifs_put_smb_ses(ses);
2182                 free_xid(xid);
2183                 return ERR_PTR(rc);
2184             }
2185 
2186             rc = cifs_setup_session(xid, ses, server,
2187                         ctx->local_nls);
2188             if (rc) {
2189                 mutex_unlock(&ses->session_mutex);
2190                 /* problem -- put our reference */
2191                 cifs_put_smb_ses(ses);
2192                 free_xid(xid);
2193                 return ERR_PTR(rc);
2194             }
2195             mutex_unlock(&ses->session_mutex);
2196 
2197             spin_lock(&ses->chan_lock);
2198         }
2199         spin_unlock(&ses->chan_lock);
2200 
2201         /* existing SMB ses has a server reference already */
2202         cifs_put_tcp_session(server, 0);
2203         free_xid(xid);
2204         return ses;
2205     }
2206 
2207     cifs_dbg(FYI, "Existing smb sess not found\n");
2208     ses = sesInfoAlloc();
2209     if (ses == NULL)
2210         goto get_ses_fail;
2211 
2212     /* new SMB session uses our server ref */
2213     ses->server = server;
2214     if (server->dstaddr.ss_family == AF_INET6)
2215         sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2216     else
2217         sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2218 
2219     if (ctx->username) {
2220         ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2221         if (!ses->user_name)
2222             goto get_ses_fail;
2223     }
2224 
2225     /* ctx->password freed at unmount */
2226     if (ctx->password) {
2227         ses->password = kstrdup(ctx->password, GFP_KERNEL);
2228         if (!ses->password)
2229             goto get_ses_fail;
2230     }
2231     if (ctx->domainname) {
2232         ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2233         if (!ses->domainName)
2234             goto get_ses_fail;
2235     }
2236 
2237     strscpy(ses->workstation_name, ctx->workstation_name, sizeof(ses->workstation_name));
2238 
2239     if (ctx->domainauto)
2240         ses->domainAuto = ctx->domainauto;
2241     ses->cred_uid = ctx->cred_uid;
2242     ses->linux_uid = ctx->linux_uid;
2243 
2244     ses->sectype = ctx->sectype;
2245     ses->sign = ctx->sign;
2246 
2247     /* add server as first channel */
2248     spin_lock(&ses->chan_lock);
2249     ses->chans[0].server = server;
2250     ses->chan_count = 1;
2251     ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2252     ses->chans_need_reconnect = 1;
2253     spin_unlock(&ses->chan_lock);
2254 
2255     mutex_lock(&ses->session_mutex);
2256     rc = cifs_negotiate_protocol(xid, ses, server);
2257     if (!rc)
2258         rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2259     mutex_unlock(&ses->session_mutex);
2260 
2261     /* each channel uses a different signing key */
2262     spin_lock(&ses->chan_lock);
2263     memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2264            sizeof(ses->smb3signingkey));
2265     spin_unlock(&ses->chan_lock);
2266 
2267     if (rc)
2268         goto get_ses_fail;
2269 
2270     /*
2271      * success, put it on the list and add it as first channel
2272      * note: the session becomes active soon after this. So you'll
2273      * need to lock before changing something in the session.
2274      */
2275     spin_lock(&cifs_tcp_ses_lock);
2276     list_add(&ses->smb_ses_list, &server->smb_ses_list);
2277     spin_unlock(&cifs_tcp_ses_lock);
2278 
2279     free_xid(xid);
2280 
2281     cifs_setup_ipc(ses, ctx);
2282 
2283     return ses;
2284 
2285 get_ses_fail:
2286     sesInfoFree(ses);
2287     free_xid(xid);
2288     return ERR_PTR(rc);
2289 }
2290 
2291 /* this function must be called with tc_lock held */
2292 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2293 {
2294     if (tcon->status == TID_EXITING)
2295         return 0;
2296     if (strncmp(tcon->treeName, ctx->UNC, MAX_TREE_SIZE))
2297         return 0;
2298     if (tcon->seal != ctx->seal)
2299         return 0;
2300     if (tcon->snapshot_time != ctx->snapshot_time)
2301         return 0;
2302     if (tcon->handle_timeout != ctx->handle_timeout)
2303         return 0;
2304     if (tcon->no_lease != ctx->no_lease)
2305         return 0;
2306     if (tcon->nodelete != ctx->nodelete)
2307         return 0;
2308     return 1;
2309 }
2310 
2311 static struct cifs_tcon *
2312 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2313 {
2314     struct cifs_tcon *tcon;
2315 
2316     spin_lock(&cifs_tcp_ses_lock);
2317     list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2318         spin_lock(&tcon->tc_lock);
2319         if (!match_tcon(tcon, ctx)) {
2320             spin_unlock(&tcon->tc_lock);
2321             continue;
2322         }
2323         ++tcon->tc_count;
2324         spin_unlock(&tcon->tc_lock);
2325         spin_unlock(&cifs_tcp_ses_lock);
2326         return tcon;
2327     }
2328     spin_unlock(&cifs_tcp_ses_lock);
2329     return NULL;
2330 }
2331 
2332 void
2333 cifs_put_tcon(struct cifs_tcon *tcon)
2334 {
2335     unsigned int xid;
2336     struct cifs_ses *ses;
2337 
2338     /*
2339      * IPC tcon share the lifetime of their session and are
2340      * destroyed in the session put function
2341      */
2342     if (tcon == NULL || tcon->ipc)
2343         return;
2344 
2345     ses = tcon->ses;
2346     cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2347     spin_lock(&cifs_tcp_ses_lock);
2348     spin_lock(&tcon->tc_lock);
2349     if (--tcon->tc_count > 0) {
2350         spin_unlock(&tcon->tc_lock);
2351         spin_unlock(&cifs_tcp_ses_lock);
2352         return;
2353     }
2354 
2355     /* tc_count can never go negative */
2356     WARN_ON(tcon->tc_count < 0);
2357 
2358     list_del_init(&tcon->tcon_list);
2359     spin_unlock(&tcon->tc_lock);
2360     spin_unlock(&cifs_tcp_ses_lock);
2361 
2362     /* cancel polling of interfaces */
2363     cancel_delayed_work_sync(&tcon->query_interfaces);
2364 
2365     if (tcon->use_witness) {
2366         int rc;
2367 
2368         rc = cifs_swn_unregister(tcon);
2369         if (rc < 0) {
2370             cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2371                     __func__, rc);
2372         }
2373     }
2374 
2375     xid = get_xid();
2376     if (ses->server->ops->tree_disconnect)
2377         ses->server->ops->tree_disconnect(xid, tcon);
2378     _free_xid(xid);
2379 
2380     cifs_fscache_release_super_cookie(tcon);
2381     tconInfoFree(tcon);
2382     cifs_put_smb_ses(ses);
2383 }
2384 
2385 /**
2386  * cifs_get_tcon - get a tcon matching @ctx data from @ses
2387  * @ses: smb session to issue the request on
2388  * @ctx: the superblock configuration context to use for building the
2389  *
2390  * - tcon refcount is the number of mount points using the tcon.
2391  * - ses refcount is the number of tcon using the session.
2392  *
2393  * 1. This function assumes it is being called from cifs_mount() where
2394  *    we already got a session reference (ses refcount +1).
2395  *
2396  * 2. Since we're in the context of adding a mount point, the end
2397  *    result should be either:
2398  *
2399  * a) a new tcon already allocated with refcount=1 (1 mount point) and
2400  *    its session refcount incremented (1 new tcon). This +1 was
2401  *    already done in (1).
2402  *
2403  * b) an existing tcon with refcount+1 (add a mount point to it) and
2404  *    identical ses refcount (no new tcon). Because of (1) we need to
2405  *    decrement the ses refcount.
2406  */
2407 static struct cifs_tcon *
2408 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2409 {
2410     int rc, xid;
2411     struct cifs_tcon *tcon;
2412 
2413     tcon = cifs_find_tcon(ses, ctx);
2414     if (tcon) {
2415         /*
2416          * tcon has refcount already incremented but we need to
2417          * decrement extra ses reference gotten by caller (case b)
2418          */
2419         cifs_dbg(FYI, "Found match on UNC path\n");
2420         cifs_put_smb_ses(ses);
2421         return tcon;
2422     }
2423 
2424     if (!ses->server->ops->tree_connect) {
2425         rc = -ENOSYS;
2426         goto out_fail;
2427     }
2428 
2429     tcon = tconInfoAlloc();
2430     if (tcon == NULL) {
2431         rc = -ENOMEM;
2432         goto out_fail;
2433     }
2434 
2435     if (ctx->snapshot_time) {
2436         if (ses->server->vals->protocol_id == 0) {
2437             cifs_dbg(VFS,
2438                  "Use SMB2 or later for snapshot mount option\n");
2439             rc = -EOPNOTSUPP;
2440             goto out_fail;
2441         } else
2442             tcon->snapshot_time = ctx->snapshot_time;
2443     }
2444 
2445     if (ctx->handle_timeout) {
2446         if (ses->server->vals->protocol_id == 0) {
2447             cifs_dbg(VFS,
2448                  "Use SMB2.1 or later for handle timeout option\n");
2449             rc = -EOPNOTSUPP;
2450             goto out_fail;
2451         } else
2452             tcon->handle_timeout = ctx->handle_timeout;
2453     }
2454 
2455     tcon->ses = ses;
2456     if (ctx->password) {
2457         tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2458         if (!tcon->password) {
2459             rc = -ENOMEM;
2460             goto out_fail;
2461         }
2462     }
2463 
2464     if (ctx->seal) {
2465         if (ses->server->vals->protocol_id == 0) {
2466             cifs_dbg(VFS,
2467                  "SMB3 or later required for encryption\n");
2468             rc = -EOPNOTSUPP;
2469             goto out_fail;
2470         } else if (tcon->ses->server->capabilities &
2471                     SMB2_GLOBAL_CAP_ENCRYPTION)
2472             tcon->seal = true;
2473         else {
2474             cifs_dbg(VFS, "Encryption is not supported on share\n");
2475             rc = -EOPNOTSUPP;
2476             goto out_fail;
2477         }
2478     }
2479 
2480     if (ctx->linux_ext) {
2481         if (ses->server->posix_ext_supported) {
2482             tcon->posix_extensions = true;
2483             pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2484         } else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
2485             (strcmp(ses->server->vals->version_string,
2486              SMB3ANY_VERSION_STRING) == 0) ||
2487             (strcmp(ses->server->vals->version_string,
2488              SMBDEFAULT_VERSION_STRING) == 0)) {
2489             cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2490             rc = -EOPNOTSUPP;
2491             goto out_fail;
2492         } else {
2493             cifs_dbg(VFS, "Check vers= mount option. SMB3.11 "
2494                 "disabled but required for POSIX extensions\n");
2495             rc = -EOPNOTSUPP;
2496             goto out_fail;
2497         }
2498     }
2499 
2500     xid = get_xid();
2501     rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2502                         ctx->local_nls);
2503     free_xid(xid);
2504     cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2505     if (rc)
2506         goto out_fail;
2507 
2508     tcon->use_persistent = false;
2509     /* check if SMB2 or later, CIFS does not support persistent handles */
2510     if (ctx->persistent) {
2511         if (ses->server->vals->protocol_id == 0) {
2512             cifs_dbg(VFS,
2513                  "SMB3 or later required for persistent handles\n");
2514             rc = -EOPNOTSUPP;
2515             goto out_fail;
2516         } else if (ses->server->capabilities &
2517                SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2518             tcon->use_persistent = true;
2519         else /* persistent handles requested but not supported */ {
2520             cifs_dbg(VFS,
2521                 "Persistent handles not supported on share\n");
2522             rc = -EOPNOTSUPP;
2523             goto out_fail;
2524         }
2525     } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2526          && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2527          && (ctx->nopersistent == false)) {
2528         cifs_dbg(FYI, "enabling persistent handles\n");
2529         tcon->use_persistent = true;
2530     } else if (ctx->resilient) {
2531         if (ses->server->vals->protocol_id == 0) {
2532             cifs_dbg(VFS,
2533                  "SMB2.1 or later required for resilient handles\n");
2534             rc = -EOPNOTSUPP;
2535             goto out_fail;
2536         }
2537         tcon->use_resilient = true;
2538     }
2539 
2540     tcon->use_witness = false;
2541     if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2542         if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2543             if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2544                 /*
2545                  * Set witness in use flag in first place
2546                  * to retry registration in the echo task
2547                  */
2548                 tcon->use_witness = true;
2549                 /* And try to register immediately */
2550                 rc = cifs_swn_register(tcon);
2551                 if (rc < 0) {
2552                     cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2553                     goto out_fail;
2554                 }
2555             } else {
2556                 /* TODO: try to extend for non-cluster uses (eg multichannel) */
2557                 cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2558                 rc = -EOPNOTSUPP;
2559                 goto out_fail;
2560             }
2561         } else {
2562             cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2563             rc = -EOPNOTSUPP;
2564             goto out_fail;
2565         }
2566     }
2567 
2568     /* If the user really knows what they are doing they can override */
2569     if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2570         if (ctx->cache_ro)
2571             cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2572         else if (ctx->cache_rw)
2573             cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2574     }
2575 
2576     if (ctx->no_lease) {
2577         if (ses->server->vals->protocol_id == 0) {
2578             cifs_dbg(VFS,
2579                 "SMB2 or later required for nolease option\n");
2580             rc = -EOPNOTSUPP;
2581             goto out_fail;
2582         } else
2583             tcon->no_lease = ctx->no_lease;
2584     }
2585 
2586     /*
2587      * We can have only one retry value for a connection to a share so for
2588      * resources mounted more than once to the same server share the last
2589      * value passed in for the retry flag is used.
2590      */
2591     tcon->retry = ctx->retry;
2592     tcon->nocase = ctx->nocase;
2593     tcon->broken_sparse_sup = ctx->no_sparse;
2594     if (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING)
2595         tcon->nohandlecache = ctx->nohandlecache;
2596     else
2597         tcon->nohandlecache = true;
2598     tcon->nodelete = ctx->nodelete;
2599     tcon->local_lease = ctx->local_lease;
2600     INIT_LIST_HEAD(&tcon->pending_opens);
2601 
2602     /* schedule query interfaces poll */
2603     INIT_DELAYED_WORK(&tcon->query_interfaces,
2604               smb2_query_server_interfaces);
2605     queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
2606                (SMB_INTERFACE_POLL_INTERVAL * HZ));
2607 
2608     spin_lock(&cifs_tcp_ses_lock);
2609     list_add(&tcon->tcon_list, &ses->tcon_list);
2610     spin_unlock(&cifs_tcp_ses_lock);
2611 
2612     return tcon;
2613 
2614 out_fail:
2615     tconInfoFree(tcon);
2616     return ERR_PTR(rc);
2617 }
2618 
2619 void
2620 cifs_put_tlink(struct tcon_link *tlink)
2621 {
2622     if (!tlink || IS_ERR(tlink))
2623         return;
2624 
2625     if (!atomic_dec_and_test(&tlink->tl_count) ||
2626         test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2627         tlink->tl_time = jiffies;
2628         return;
2629     }
2630 
2631     if (!IS_ERR(tlink_tcon(tlink)))
2632         cifs_put_tcon(tlink_tcon(tlink));
2633     kfree(tlink);
2634     return;
2635 }
2636 
2637 static int
2638 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2639 {
2640     struct cifs_sb_info *old = CIFS_SB(sb);
2641     struct cifs_sb_info *new = mnt_data->cifs_sb;
2642     unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2643     unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2644 
2645     if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2646         return 0;
2647 
2648     if (old->mnt_cifs_serverino_autodisabled)
2649         newflags &= ~CIFS_MOUNT_SERVER_INUM;
2650 
2651     if (oldflags != newflags)
2652         return 0;
2653 
2654     /*
2655      * We want to share sb only if we don't specify an r/wsize or
2656      * specified r/wsize is greater than or equal to existing one.
2657      */
2658     if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2659         return 0;
2660 
2661     if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2662         return 0;
2663 
2664     if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2665         !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2666         return 0;
2667 
2668     if (old->ctx->file_mode != new->ctx->file_mode ||
2669         old->ctx->dir_mode != new->ctx->dir_mode)
2670         return 0;
2671 
2672     if (strcmp(old->local_nls->charset, new->local_nls->charset))
2673         return 0;
2674 
2675     if (old->ctx->acregmax != new->ctx->acregmax)
2676         return 0;
2677     if (old->ctx->acdirmax != new->ctx->acdirmax)
2678         return 0;
2679     if (old->ctx->closetimeo != new->ctx->closetimeo)
2680         return 0;
2681 
2682     return 1;
2683 }
2684 
2685 static int
2686 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2687 {
2688     struct cifs_sb_info *old = CIFS_SB(sb);
2689     struct cifs_sb_info *new = mnt_data->cifs_sb;
2690     bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2691         old->prepath;
2692     bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2693         new->prepath;
2694 
2695     if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2696         return 1;
2697     else if (!old_set && !new_set)
2698         return 1;
2699 
2700     return 0;
2701 }
2702 
2703 int
2704 cifs_match_super(struct super_block *sb, void *data)
2705 {
2706     struct cifs_mnt_data *mnt_data = data;
2707     struct smb3_fs_context *ctx;
2708     struct cifs_sb_info *cifs_sb;
2709     struct TCP_Server_Info *tcp_srv;
2710     struct cifs_ses *ses;
2711     struct cifs_tcon *tcon;
2712     struct tcon_link *tlink;
2713     int rc = 0;
2714 
2715     spin_lock(&cifs_tcp_ses_lock);
2716     cifs_sb = CIFS_SB(sb);
2717     tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2718     if (tlink == NULL) {
2719         /* can not match superblock if tlink were ever null */
2720         spin_unlock(&cifs_tcp_ses_lock);
2721         return 0;
2722     }
2723     tcon = tlink_tcon(tlink);
2724     ses = tcon->ses;
2725     tcp_srv = ses->server;
2726 
2727     ctx = mnt_data->ctx;
2728 
2729     spin_lock(&tcp_srv->srv_lock);
2730     spin_lock(&ses->ses_lock);
2731     spin_lock(&tcon->tc_lock);
2732     if (!match_server(tcp_srv, ctx) ||
2733         !match_session(ses, ctx) ||
2734         !match_tcon(tcon, ctx) ||
2735         !match_prepath(sb, mnt_data)) {
2736         rc = 0;
2737         goto out;
2738     }
2739 
2740     rc = compare_mount_options(sb, mnt_data);
2741 out:
2742     spin_unlock(&tcon->tc_lock);
2743     spin_unlock(&ses->ses_lock);
2744     spin_unlock(&tcp_srv->srv_lock);
2745 
2746     spin_unlock(&cifs_tcp_ses_lock);
2747     cifs_put_tlink(tlink);
2748     return rc;
2749 }
2750 
2751 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2752 static struct lock_class_key cifs_key[2];
2753 static struct lock_class_key cifs_slock_key[2];
2754 
2755 static inline void
2756 cifs_reclassify_socket4(struct socket *sock)
2757 {
2758     struct sock *sk = sock->sk;
2759     BUG_ON(!sock_allow_reclassification(sk));
2760     sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2761         &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2762 }
2763 
2764 static inline void
2765 cifs_reclassify_socket6(struct socket *sock)
2766 {
2767     struct sock *sk = sock->sk;
2768     BUG_ON(!sock_allow_reclassification(sk));
2769     sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2770         &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2771 }
2772 #else
2773 static inline void
2774 cifs_reclassify_socket4(struct socket *sock)
2775 {
2776 }
2777 
2778 static inline void
2779 cifs_reclassify_socket6(struct socket *sock)
2780 {
2781 }
2782 #endif
2783 
2784 /* See RFC1001 section 14 on representation of Netbios names */
2785 static void rfc1002mangle(char *target, char *source, unsigned int length)
2786 {
2787     unsigned int i, j;
2788 
2789     for (i = 0, j = 0; i < (length); i++) {
2790         /* mask a nibble at a time and encode */
2791         target[j] = 'A' + (0x0F & (source[i] >> 4));
2792         target[j+1] = 'A' + (0x0F & source[i]);
2793         j += 2;
2794     }
2795 
2796 }
2797 
2798 static int
2799 bind_socket(struct TCP_Server_Info *server)
2800 {
2801     int rc = 0;
2802     if (server->srcaddr.ss_family != AF_UNSPEC) {
2803         /* Bind to the specified local IP address */
2804         struct socket *socket = server->ssocket;
2805         rc = socket->ops->bind(socket,
2806                        (struct sockaddr *) &server->srcaddr,
2807                        sizeof(server->srcaddr));
2808         if (rc < 0) {
2809             struct sockaddr_in *saddr4;
2810             struct sockaddr_in6 *saddr6;
2811             saddr4 = (struct sockaddr_in *)&server->srcaddr;
2812             saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2813             if (saddr6->sin6_family == AF_INET6)
2814                 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2815                      &saddr6->sin6_addr, rc);
2816             else
2817                 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2818                      &saddr4->sin_addr.s_addr, rc);
2819         }
2820     }
2821     return rc;
2822 }
2823 
2824 static int
2825 ip_rfc1001_connect(struct TCP_Server_Info *server)
2826 {
2827     int rc = 0;
2828     /*
2829      * some servers require RFC1001 sessinit before sending
2830      * negprot - BB check reconnection in case where second
2831      * sessinit is sent but no second negprot
2832      */
2833     struct rfc1002_session_packet *ses_init_buf;
2834     struct smb_hdr *smb_buf;
2835     ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
2836                    GFP_KERNEL);
2837     if (ses_init_buf) {
2838         ses_init_buf->trailer.session_req.called_len = 32;
2839 
2840         if (server->server_RFC1001_name[0] != 0)
2841             rfc1002mangle(ses_init_buf->trailer.
2842                       session_req.called_name,
2843                       server->server_RFC1001_name,
2844                       RFC1001_NAME_LEN_WITH_NULL);
2845         else
2846             rfc1002mangle(ses_init_buf->trailer.
2847                       session_req.called_name,
2848                       DEFAULT_CIFS_CALLED_NAME,
2849                       RFC1001_NAME_LEN_WITH_NULL);
2850 
2851         ses_init_buf->trailer.session_req.calling_len = 32;
2852 
2853         /*
2854          * calling name ends in null (byte 16) from old smb
2855          * convention.
2856          */
2857         if (server->workstation_RFC1001_name[0] != 0)
2858             rfc1002mangle(ses_init_buf->trailer.
2859                       session_req.calling_name,
2860                       server->workstation_RFC1001_name,
2861                       RFC1001_NAME_LEN_WITH_NULL);
2862         else
2863             rfc1002mangle(ses_init_buf->trailer.
2864                       session_req.calling_name,
2865                       "LINUX_CIFS_CLNT",
2866                       RFC1001_NAME_LEN_WITH_NULL);
2867 
2868         ses_init_buf->trailer.session_req.scope1 = 0;
2869         ses_init_buf->trailer.session_req.scope2 = 0;
2870         smb_buf = (struct smb_hdr *)ses_init_buf;
2871 
2872         /* sizeof RFC1002_SESSION_REQUEST with no scope */
2873         smb_buf->smb_buf_length = cpu_to_be32(0x81000044);
2874         rc = smb_send(server, smb_buf, 0x44);
2875         kfree(ses_init_buf);
2876         /*
2877          * RFC1001 layer in at least one server
2878          * requires very short break before negprot
2879          * presumably because not expecting negprot
2880          * to follow so fast.  This is a simple
2881          * solution that works without
2882          * complicating the code and causes no
2883          * significant slowing down on mount
2884          * for everyone else
2885          */
2886         usleep_range(1000, 2000);
2887     }
2888     /*
2889      * else the negprot may still work without this
2890      * even though malloc failed
2891      */
2892 
2893     return rc;
2894 }
2895 
2896 static int
2897 generic_ip_connect(struct TCP_Server_Info *server)
2898 {
2899     int rc = 0;
2900     __be16 sport;
2901     int slen, sfamily;
2902     struct socket *socket = server->ssocket;
2903     struct sockaddr *saddr;
2904 
2905     saddr = (struct sockaddr *) &server->dstaddr;
2906 
2907     if (server->dstaddr.ss_family == AF_INET6) {
2908         struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
2909 
2910         sport = ipv6->sin6_port;
2911         slen = sizeof(struct sockaddr_in6);
2912         sfamily = AF_INET6;
2913         cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
2914                 ntohs(sport));
2915     } else {
2916         struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
2917 
2918         sport = ipv4->sin_port;
2919         slen = sizeof(struct sockaddr_in);
2920         sfamily = AF_INET;
2921         cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
2922                 ntohs(sport));
2923     }
2924 
2925     if (socket == NULL) {
2926         rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
2927                    IPPROTO_TCP, &socket, 1);
2928         if (rc < 0) {
2929             cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
2930             server->ssocket = NULL;
2931             return rc;
2932         }
2933 
2934         /* BB other socket options to set KEEPALIVE, NODELAY? */
2935         cifs_dbg(FYI, "Socket created\n");
2936         server->ssocket = socket;
2937         socket->sk->sk_allocation = GFP_NOFS;
2938         if (sfamily == AF_INET6)
2939             cifs_reclassify_socket6(socket);
2940         else
2941             cifs_reclassify_socket4(socket);
2942     }
2943 
2944     rc = bind_socket(server);
2945     if (rc < 0)
2946         return rc;
2947 
2948     /*
2949      * Eventually check for other socket options to change from
2950      * the default. sock_setsockopt not used because it expects
2951      * user space buffer
2952      */
2953     socket->sk->sk_rcvtimeo = 7 * HZ;
2954     socket->sk->sk_sndtimeo = 5 * HZ;
2955 
2956     /* make the bufsizes depend on wsize/rsize and max requests */
2957     if (server->noautotune) {
2958         if (socket->sk->sk_sndbuf < (200 * 1024))
2959             socket->sk->sk_sndbuf = 200 * 1024;
2960         if (socket->sk->sk_rcvbuf < (140 * 1024))
2961             socket->sk->sk_rcvbuf = 140 * 1024;
2962     }
2963 
2964     if (server->tcp_nodelay)
2965         tcp_sock_set_nodelay(socket->sk);
2966 
2967     cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
2968          socket->sk->sk_sndbuf,
2969          socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
2970 
2971     rc = socket->ops->connect(socket, saddr, slen,
2972                   server->noblockcnt ? O_NONBLOCK : 0);
2973     /*
2974      * When mounting SMB root file systems, we do not want to block in
2975      * connect. Otherwise bail out and then let cifs_reconnect() perform
2976      * reconnect failover - if possible.
2977      */
2978     if (server->noblockcnt && rc == -EINPROGRESS)
2979         rc = 0;
2980     if (rc < 0) {
2981         cifs_dbg(FYI, "Error %d connecting to server\n", rc);
2982         trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
2983         sock_release(socket);
2984         server->ssocket = NULL;
2985         return rc;
2986     }
2987     trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
2988     if (sport == htons(RFC1001_PORT))
2989         rc = ip_rfc1001_connect(server);
2990 
2991     return rc;
2992 }
2993 
2994 static int
2995 ip_connect(struct TCP_Server_Info *server)
2996 {
2997     __be16 *sport;
2998     struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2999     struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3000 
3001     if (server->dstaddr.ss_family == AF_INET6)
3002         sport = &addr6->sin6_port;
3003     else
3004         sport = &addr->sin_port;
3005 
3006     if (*sport == 0) {
3007         int rc;
3008 
3009         /* try with 445 port at first */
3010         *sport = htons(CIFS_PORT);
3011 
3012         rc = generic_ip_connect(server);
3013         if (rc >= 0)
3014             return rc;
3015 
3016         /* if it failed, try with 139 port */
3017         *sport = htons(RFC1001_PORT);
3018     }
3019 
3020     return generic_ip_connect(server);
3021 }
3022 
3023 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3024 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3025               struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3026 {
3027     /*
3028      * If we are reconnecting then should we check to see if
3029      * any requested capabilities changed locally e.g. via
3030      * remount but we can not do much about it here
3031      * if they have (even if we could detect it by the following)
3032      * Perhaps we could add a backpointer to array of sb from tcon
3033      * or if we change to make all sb to same share the same
3034      * sb as NFS - then we only have one backpointer to sb.
3035      * What if we wanted to mount the server share twice once with
3036      * and once without posixacls or posix paths?
3037      */
3038     __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3039 
3040     if (ctx && ctx->no_linux_ext) {
3041         tcon->fsUnixInfo.Capability = 0;
3042         tcon->unix_ext = 0; /* Unix Extensions disabled */
3043         cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3044         return;
3045     } else if (ctx)
3046         tcon->unix_ext = 1; /* Unix Extensions supported */
3047 
3048     if (!tcon->unix_ext) {
3049         cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3050         return;
3051     }
3052 
3053     if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3054         __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3055         cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3056         /*
3057          * check for reconnect case in which we do not
3058          * want to change the mount behavior if we can avoid it
3059          */
3060         if (ctx == NULL) {
3061             /*
3062              * turn off POSIX ACL and PATHNAMES if not set
3063              * originally at mount time
3064              */
3065             if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3066                 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3067             if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3068                 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3069                     cifs_dbg(VFS, "POSIXPATH support change\n");
3070                 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3071             } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3072                 cifs_dbg(VFS, "possible reconnect error\n");
3073                 cifs_dbg(VFS, "server disabled POSIX path support\n");
3074             }
3075         }
3076 
3077         if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3078             cifs_dbg(VFS, "per-share encryption not supported yet\n");
3079 
3080         cap &= CIFS_UNIX_CAP_MASK;
3081         if (ctx && ctx->no_psx_acl)
3082             cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3083         else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3084             cifs_dbg(FYI, "negotiated posix acl support\n");
3085             if (cifs_sb)
3086                 cifs_sb->mnt_cifs_flags |=
3087                     CIFS_MOUNT_POSIXACL;
3088         }
3089 
3090         if (ctx && ctx->posix_paths == 0)
3091             cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3092         else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3093             cifs_dbg(FYI, "negotiate posix pathnames\n");
3094             if (cifs_sb)
3095                 cifs_sb->mnt_cifs_flags |=
3096                     CIFS_MOUNT_POSIX_PATHS;
3097         }
3098 
3099         cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3100 #ifdef CONFIG_CIFS_DEBUG2
3101         if (cap & CIFS_UNIX_FCNTL_CAP)
3102             cifs_dbg(FYI, "FCNTL cap\n");
3103         if (cap & CIFS_UNIX_EXTATTR_CAP)
3104             cifs_dbg(FYI, "EXTATTR cap\n");
3105         if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3106             cifs_dbg(FYI, "POSIX path cap\n");
3107         if (cap & CIFS_UNIX_XATTR_CAP)
3108             cifs_dbg(FYI, "XATTR cap\n");
3109         if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3110             cifs_dbg(FYI, "POSIX ACL cap\n");
3111         if (cap & CIFS_UNIX_LARGE_READ_CAP)
3112             cifs_dbg(FYI, "very large read cap\n");
3113         if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3114             cifs_dbg(FYI, "very large write cap\n");
3115         if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3116             cifs_dbg(FYI, "transport encryption cap\n");
3117         if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3118             cifs_dbg(FYI, "mandatory transport encryption cap\n");
3119 #endif /* CIFS_DEBUG2 */
3120         if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3121             if (ctx == NULL)
3122                 cifs_dbg(FYI, "resetting capabilities failed\n");
3123             else
3124                 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");
3125 
3126         }
3127     }
3128 }
3129 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3130 
3131 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3132 {
3133     struct smb3_fs_context *ctx = cifs_sb->ctx;
3134 
3135     INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3136 
3137     spin_lock_init(&cifs_sb->tlink_tree_lock);
3138     cifs_sb->tlink_tree = RB_ROOT;
3139 
3140     cifs_dbg(FYI, "file mode: %04ho  dir mode: %04ho\n",
3141          ctx->file_mode, ctx->dir_mode);
3142 
3143     /* this is needed for ASCII cp to Unicode converts */
3144     if (ctx->iocharset == NULL) {
3145         /* load_nls_default cannot return null */
3146         cifs_sb->local_nls = load_nls_default();
3147     } else {
3148         cifs_sb->local_nls = load_nls(ctx->iocharset);
3149         if (cifs_sb->local_nls == NULL) {
3150             cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3151                  ctx->iocharset);
3152             return -ELIBACC;
3153         }
3154     }
3155     ctx->local_nls = cifs_sb->local_nls;
3156 
3157     smb3_update_mnt_flags(cifs_sb);
3158 
3159     if (ctx->direct_io)
3160         cifs_dbg(FYI, "mounting share using direct i/o\n");
3161     if (ctx->cache_ro) {
3162         cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
3163         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3164     } else if (ctx->cache_rw) {
3165         cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
3166         cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
3167                         CIFS_MOUNT_RW_CACHE);
3168     }
3169 
3170     if ((ctx->cifs_acl) && (ctx->dynperm))
3171         cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3172 
3173     if (ctx->prepath) {
3174         cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3175         if (cifs_sb->prepath == NULL)
3176             return -ENOMEM;
3177         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3178     }
3179 
3180     return 0;
3181 }
3182 
3183 /* Release all succeed connections */
3184 static inline void mount_put_conns(struct mount_ctx *mnt_ctx)
3185 {
3186     int rc = 0;
3187 
3188     if (mnt_ctx->tcon)
3189         cifs_put_tcon(mnt_ctx->tcon);
3190     else if (mnt_ctx->ses)
3191         cifs_put_smb_ses(mnt_ctx->ses);
3192     else if (mnt_ctx->server)
3193         cifs_put_tcp_session(mnt_ctx->server, 0);
3194     mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3195     free_xid(mnt_ctx->xid);
3196 }
3197 
3198 /* Get connections for tcp, ses and tcon */
3199 static int mount_get_conns(struct mount_ctx *mnt_ctx)
3200 {
3201     int rc = 0;
3202     struct TCP_Server_Info *server = NULL;
3203     struct cifs_ses *ses = NULL;
3204     struct cifs_tcon *tcon = NULL;
3205     struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3206     struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3207     unsigned int xid;
3208 
3209     xid = get_xid();
3210 
3211     /* get a reference to a tcp session */
3212     server = cifs_get_tcp_session(ctx, NULL);
3213     if (IS_ERR(server)) {
3214         rc = PTR_ERR(server);
3215         server = NULL;
3216         goto out;
3217     }
3218 
3219     /* get a reference to a SMB session */
3220     ses = cifs_get_smb_ses(server, ctx);
3221     if (IS_ERR(ses)) {
3222         rc = PTR_ERR(ses);
3223         ses = NULL;
3224         goto out;
3225     }
3226 
3227     if ((ctx->persistent == true) && (!(ses->server->capabilities &
3228                         SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3229         cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3230         rc = -EOPNOTSUPP;
3231         goto out;
3232     }
3233 
3234     /* search for existing tcon to this server share */
3235     tcon = cifs_get_tcon(ses, ctx);
3236     if (IS_ERR(tcon)) {
3237         rc = PTR_ERR(tcon);
3238         tcon = NULL;
3239         goto out;
3240     }
3241 
3242     /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3243     if (tcon->posix_extensions)
3244         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3245 
3246 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3247     /* tell server which Unix caps we support */
3248     if (cap_unix(tcon->ses)) {
3249         /*
3250          * reset of caps checks mount to see if unix extensions disabled
3251          * for just this mount.
3252          */
3253         reset_cifs_unix_caps(xid, tcon, cifs_sb, ctx);
3254         spin_lock(&tcon->ses->server->srv_lock);
3255         if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3256             (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3257              CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3258             spin_unlock(&tcon->ses->server->srv_lock);
3259             rc = -EACCES;
3260             goto out;
3261         }
3262         spin_unlock(&tcon->ses->server->srv_lock);
3263     } else
3264 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3265         tcon->unix_ext = 0; /* server does not support them */
3266 
3267     /* do not care if a following call succeed - informational */
3268     if (!tcon->pipe && server->ops->qfs_tcon) {
3269         server->ops->qfs_tcon(xid, tcon, cifs_sb);
3270         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3271             if (tcon->fsDevInfo.DeviceCharacteristics &
3272                 cpu_to_le32(FILE_READ_ONLY_DEVICE))
3273                 cifs_dbg(VFS, "mounted to read only share\n");
3274             else if ((cifs_sb->mnt_cifs_flags &
3275                   CIFS_MOUNT_RW_CACHE) == 0)
3276                 cifs_dbg(VFS, "read only mount of RW share\n");
3277             /* no need to log a RW mount of a typical RW share */
3278         }
3279     }
3280 
3281     /*
3282      * Clamp the rsize/wsize mount arguments if they are too big for the server
3283      * and set the rsize/wsize to the negotiated values if not passed in by
3284      * the user on mount
3285      */
3286     if ((cifs_sb->ctx->wsize == 0) ||
3287         (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
3288         cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
3289     if ((cifs_sb->ctx->rsize == 0) ||
3290         (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3291         cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3292 
3293     /*
3294      * The cookie is initialized from volume info returned above.
3295      * Inside cifs_fscache_get_super_cookie it checks
3296      * that we do not get super cookie twice.
3297      */
3298     if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
3299         cifs_fscache_get_super_cookie(tcon);
3300 
3301 out:
3302     mnt_ctx->server = server;
3303     mnt_ctx->ses = ses;
3304     mnt_ctx->tcon = tcon;
3305     mnt_ctx->xid = xid;
3306 
3307     return rc;
3308 }
3309 
3310 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3311                  struct cifs_tcon *tcon)
3312 {
3313     struct tcon_link *tlink;
3314 
3315     /* hang the tcon off of the superblock */
3316     tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3317     if (tlink == NULL)
3318         return -ENOMEM;
3319 
3320     tlink->tl_uid = ses->linux_uid;
3321     tlink->tl_tcon = tcon;
3322     tlink->tl_time = jiffies;
3323     set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3324     set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3325 
3326     cifs_sb->master_tlink = tlink;
3327     spin_lock(&cifs_sb->tlink_tree_lock);
3328     tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3329     spin_unlock(&cifs_sb->tlink_tree_lock);
3330 
3331     queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3332                 TLINK_IDLE_EXPIRE);
3333     return 0;
3334 }
3335 
3336 #ifdef CONFIG_CIFS_DFS_UPCALL
3337 /* Get unique dfs connections */
3338 static int mount_get_dfs_conns(struct mount_ctx *mnt_ctx)
3339 {
3340     int rc;
3341 
3342     mnt_ctx->fs_ctx->nosharesock = true;
3343     rc = mount_get_conns(mnt_ctx);
3344     if (mnt_ctx->server) {
3345         cifs_dbg(FYI, "%s: marking tcp session as a dfs connection\n", __func__);
3346         spin_lock(&mnt_ctx->server->srv_lock);
3347         mnt_ctx->server->is_dfs_conn = true;
3348         spin_unlock(&mnt_ctx->server->srv_lock);
3349     }
3350     return rc;
3351 }
3352 
3353 /*
3354  * cifs_build_path_to_root returns full path to root when we do not have an
3355  * existing connection (tcon)
3356  */
3357 static char *
3358 build_unc_path_to_root(const struct smb3_fs_context *ctx,
3359                const struct cifs_sb_info *cifs_sb, bool useppath)
3360 {
3361     char *full_path, *pos;
3362     unsigned int pplen = useppath && ctx->prepath ?
3363         strlen(ctx->prepath) + 1 : 0;
3364     unsigned int unc_len = strnlen(ctx->UNC, MAX_TREE_SIZE + 1);
3365 
3366     if (unc_len > MAX_TREE_SIZE)
3367         return ERR_PTR(-EINVAL);
3368 
3369     full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
3370     if (full_path == NULL)
3371         return ERR_PTR(-ENOMEM);
3372 
3373     memcpy(full_path, ctx->UNC, unc_len);
3374     pos = full_path + unc_len;
3375 
3376     if (pplen) {
3377         *pos = CIFS_DIR_SEP(cifs_sb);
3378         memcpy(pos + 1, ctx->prepath, pplen);
3379         pos += pplen;
3380     }
3381 
3382     *pos = '\0'; /* add trailing null */
3383     convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
3384     cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
3385     return full_path;
3386 }
3387 
3388 /*
3389  * expand_dfs_referral - Update cifs_sb from dfs referral path
3390  *
3391  * cifs_sb->ctx->mount_options will be (re-)allocated to a string containing updated options for the
3392  * submount.  Otherwise it will be left untouched.
3393  */
3394 static int expand_dfs_referral(struct mount_ctx *mnt_ctx, const char *full_path,
3395                    struct dfs_info3_param *referral)
3396 {
3397     int rc;
3398     struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3399     struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3400     char *fake_devname = NULL, *mdata = NULL;
3401 
3402     mdata = cifs_compose_mount_options(cifs_sb->ctx->mount_options, full_path + 1, referral,
3403                        &fake_devname);
3404     if (IS_ERR(mdata)) {
3405         rc = PTR_ERR(mdata);
3406         mdata = NULL;
3407     } else {
3408         /*
3409          * We can not clear out the whole structure since we no longer have an explicit
3410          * function to parse a mount-string. Instead we need to clear out the individual
3411          * fields that are no longer valid.
3412          */
3413         kfree(ctx->prepath);
3414         ctx->prepath = NULL;
3415         rc = cifs_setup_volume_info(ctx, mdata, fake_devname);
3416     }
3417     kfree(fake_devname);
3418     kfree(cifs_sb->ctx->mount_options);
3419     cifs_sb->ctx->mount_options = mdata;
3420 
3421     return rc;
3422 }
3423 #endif
3424 
3425 /* TODO: all callers to this are broken. We are not parsing mount_options here
3426  * we should pass a clone of the original context?
3427  */
3428 int
3429 cifs_setup_volume_info(struct smb3_fs_context *ctx, const char *mntopts, const char *devname)
3430 {
3431     int rc;
3432 
3433     if (devname) {
3434         cifs_dbg(FYI, "%s: devname=%s\n", __func__, devname);
3435         rc = smb3_parse_devname(devname, ctx);
3436         if (rc) {
3437             cifs_dbg(VFS, "%s: failed to parse %s: %d\n", __func__, devname, rc);
3438             return rc;
3439         }
3440     }
3441 
3442     if (mntopts) {
3443         char *ip;
3444 
3445         rc = smb3_parse_opt(mntopts, "ip", &ip);
3446         if (rc) {
3447             cifs_dbg(VFS, "%s: failed to parse ip options: %d\n", __func__, rc);
3448             return rc;
3449         }
3450 
3451         rc = cifs_convert_address((struct sockaddr *)&ctx->dstaddr, ip, strlen(ip));
3452         kfree(ip);
3453         if (!rc) {
3454             cifs_dbg(VFS, "%s: failed to convert ip address\n", __func__);
3455             return -EINVAL;
3456         }
3457     }
3458 
3459     if (ctx->nullauth) {
3460         cifs_dbg(FYI, "Anonymous login\n");
3461         kfree(ctx->username);
3462         ctx->username = NULL;
3463     } else if (ctx->username) {
3464         /* BB fixme parse for domain name here */
3465         cifs_dbg(FYI, "Username: %s\n", ctx->username);
3466     } else {
3467         cifs_dbg(VFS, "No username specified\n");
3468     /* In userspace mount helper we can get user name from alternate
3469        locations such as env variables and files on disk */
3470         return -EINVAL;
3471     }
3472 
3473     return 0;
3474 }
3475 
3476 static int
3477 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3478                     unsigned int xid,
3479                     struct cifs_tcon *tcon,
3480                     struct cifs_sb_info *cifs_sb,
3481                     char *full_path,
3482                     int added_treename)
3483 {
3484     int rc;
3485     char *s;
3486     char sep, tmp;
3487     int skip = added_treename ? 1 : 0;
3488 
3489     sep = CIFS_DIR_SEP(cifs_sb);
3490     s = full_path;
3491 
3492     rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3493     while (rc == 0) {
3494         /* skip separators */
3495         while (*s == sep)
3496             s++;
3497         if (!*s)
3498             break;
3499         /* next separator */
3500         while (*s && *s != sep)
3501             s++;
3502         /*
3503          * if the treename is added, we then have to skip the first
3504          * part within the separators
3505          */
3506         if (skip) {
3507             skip = 0;
3508             continue;
3509         }
3510         /*
3511          * temporarily null-terminate the path at the end of
3512          * the current component
3513          */
3514         tmp = *s;
3515         *s = 0;
3516         rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3517                              full_path);
3518         *s = tmp;
3519     }
3520     return rc;
3521 }
3522 
3523 /*
3524  * Check if path is remote (i.e. a DFS share).
3525  *
3526  * Return -EREMOTE if it is, otherwise 0 or -errno.
3527  */
3528 static int is_path_remote(struct mount_ctx *mnt_ctx)
3529 {
3530     int rc;
3531     struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3532     struct TCP_Server_Info *server = mnt_ctx->server;
3533     unsigned int xid = mnt_ctx->xid;
3534     struct cifs_tcon *tcon = mnt_ctx->tcon;
3535     struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3536     char *full_path;
3537 #ifdef CONFIG_CIFS_DFS_UPCALL
3538     bool nodfs = cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS;
3539 #endif
3540 
3541     if (!server->ops->is_path_accessible)
3542         return -EOPNOTSUPP;
3543 
3544     /*
3545      * cifs_build_path_to_root works only when we have a valid tcon
3546      */
3547     full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3548                         tcon->Flags & SMB_SHARE_IS_IN_DFS);
3549     if (full_path == NULL)
3550         return -ENOMEM;
3551 
3552     cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3553 
3554     rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3555                          full_path);
3556 #ifdef CONFIG_CIFS_DFS_UPCALL
3557     if (nodfs) {
3558         if (rc == -EREMOTE)
3559             rc = -EOPNOTSUPP;
3560         goto out;
3561     }
3562 
3563     /* path *might* exist with non-ASCII characters in DFS root
3564      * try again with full path (only if nodfs is not set) */
3565     if (rc == -ENOENT && is_tcon_dfs(tcon))
3566         rc = cifs_dfs_query_info_nonascii_quirk(xid, tcon, cifs_sb,
3567                             full_path);
3568 #endif
3569     if (rc != 0 && rc != -EREMOTE)
3570         goto out;
3571 
3572     if (rc != -EREMOTE) {
3573         rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3574             cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3575         if (rc != 0) {
3576             cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3577             cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3578             rc = 0;
3579         }
3580     }
3581 
3582 out:
3583     kfree(full_path);
3584     return rc;
3585 }
3586 
3587 #ifdef CONFIG_CIFS_DFS_UPCALL
3588 static void set_root_ses(struct mount_ctx *mnt_ctx)
3589 {
3590     if (mnt_ctx->ses) {
3591         spin_lock(&cifs_tcp_ses_lock);
3592         mnt_ctx->ses->ses_count++;
3593         spin_unlock(&cifs_tcp_ses_lock);
3594         dfs_cache_add_refsrv_session(&mnt_ctx->mount_id, mnt_ctx->ses);
3595     }
3596     mnt_ctx->root_ses = mnt_ctx->ses;
3597 }
3598 
3599 static int is_dfs_mount(struct mount_ctx *mnt_ctx, bool *isdfs, struct dfs_cache_tgt_list *root_tl)
3600 {
3601     int rc;
3602     struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3603     struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3604 
3605     *isdfs = true;
3606 
3607     rc = mount_get_conns(mnt_ctx);
3608     /*
3609      * If called with 'nodfs' mount option, then skip DFS resolving.  Otherwise unconditionally
3610      * try to get an DFS referral (even cached) to determine whether it is an DFS mount.
3611      *
3612      * Skip prefix path to provide support for DFS referrals from w2k8 servers which don't seem
3613      * to respond with PATH_NOT_COVERED to requests that include the prefix.
3614      */
3615     if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
3616         dfs_cache_find(mnt_ctx->xid, mnt_ctx->ses, cifs_sb->local_nls, cifs_remap(cifs_sb),
3617                ctx->UNC + 1, NULL, root_tl)) {
3618         if (rc)
3619             return rc;
3620         /* Check if it is fully accessible and then mount it */
3621         rc = is_path_remote(mnt_ctx);
3622         if (!rc)
3623             *isdfs = false;
3624         else if (rc != -EREMOTE)
3625             return rc;
3626     }
3627     return 0;
3628 }
3629 
3630 static int connect_dfs_target(struct mount_ctx *mnt_ctx, const char *full_path,
3631                   const char *ref_path, struct dfs_cache_tgt_iterator *tit)
3632 {
3633     int rc;
3634     struct dfs_info3_param ref = {};
3635     struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3636     char *oldmnt = cifs_sb->ctx->mount_options;
3637 
3638     cifs_dbg(FYI, "%s: full_path=%s ref_path=%s target=%s\n", __func__, full_path, ref_path,
3639          dfs_cache_get_tgt_name(tit));
3640 
3641     rc = dfs_cache_get_tgt_referral(ref_path, tit, &ref);
3642     if (rc)
3643         goto out;
3644 
3645     rc = expand_dfs_referral(mnt_ctx, full_path, &ref);
3646     if (rc)
3647         goto out;
3648 
3649     /* Connect to new target only if we were redirected (e.g. mount options changed) */
3650     if (oldmnt != cifs_sb->ctx->mount_options) {
3651         mount_put_conns(mnt_ctx);
3652         rc = mount_get_dfs_conns(mnt_ctx);
3653     }
3654     if (!rc) {
3655         if (cifs_is_referral_server(mnt_ctx->tcon, &ref))
3656             set_root_ses(mnt_ctx);
3657         rc = dfs_cache_update_tgthint(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3658                           cifs_remap(cifs_sb), ref_path, tit);
3659     }
3660 
3661 out:
3662     free_dfs_info_param(&ref);
3663     return rc;
3664 }
3665 
3666 static int connect_dfs_root(struct mount_ctx *mnt_ctx, struct dfs_cache_tgt_list *root_tl)
3667 {
3668     int rc;
3669     char *full_path;
3670     struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3671     struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3672     struct dfs_cache_tgt_iterator *tit;
3673 
3674     /* Put initial connections as they might be shared with other mounts.  We need unique dfs
3675      * connections per mount to properly failover, so mount_get_dfs_conns() must be used from
3676      * now on.
3677      */
3678     mount_put_conns(mnt_ctx);
3679     mount_get_dfs_conns(mnt_ctx);
3680     set_root_ses(mnt_ctx);
3681 
3682     full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3683     if (IS_ERR(full_path))
3684         return PTR_ERR(full_path);
3685 
3686     mnt_ctx->origin_fullpath = dfs_cache_canonical_path(ctx->UNC, cifs_sb->local_nls,
3687                                 cifs_remap(cifs_sb));
3688     if (IS_ERR(mnt_ctx->origin_fullpath)) {
3689         rc = PTR_ERR(mnt_ctx->origin_fullpath);
3690         mnt_ctx->origin_fullpath = NULL;
3691         goto out;
3692     }
3693 
3694     /* Try all dfs root targets */
3695     for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(root_tl);
3696          tit; tit = dfs_cache_get_next_tgt(root_tl, tit)) {
3697         rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->origin_fullpath + 1, tit);
3698         if (!rc) {
3699             mnt_ctx->leaf_fullpath = kstrdup(mnt_ctx->origin_fullpath, GFP_KERNEL);
3700             if (!mnt_ctx->leaf_fullpath)
3701                 rc = -ENOMEM;
3702             break;
3703         }
3704     }
3705 
3706 out:
3707     kfree(full_path);
3708     return rc;
3709 }
3710 
3711 static int __follow_dfs_link(struct mount_ctx *mnt_ctx)
3712 {
3713     int rc;
3714     struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3715     struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3716     char *full_path;
3717     struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3718     struct dfs_cache_tgt_iterator *tit;
3719 
3720     full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3721     if (IS_ERR(full_path))
3722         return PTR_ERR(full_path);
3723 
3724     kfree(mnt_ctx->leaf_fullpath);
3725     mnt_ctx->leaf_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3726                               cifs_remap(cifs_sb));
3727     if (IS_ERR(mnt_ctx->leaf_fullpath)) {
3728         rc = PTR_ERR(mnt_ctx->leaf_fullpath);
3729         mnt_ctx->leaf_fullpath = NULL;
3730         goto out;
3731     }
3732 
3733     /* Get referral from dfs link */
3734     rc = dfs_cache_find(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3735                 cifs_remap(cifs_sb), mnt_ctx->leaf_fullpath + 1, NULL, &tl);
3736     if (rc)
3737         goto out;
3738 
3739     /* Try all dfs link targets.  If an I/O fails from currently connected DFS target with an
3740      * error other than STATUS_PATH_NOT_COVERED (-EREMOTE), then retry it from other targets as
3741      * specified in MS-DFSC "3.1.5.2 I/O Operation to Target Fails with an Error Other Than
3742      * STATUS_PATH_NOT_COVERED."
3743      */
3744     for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(&tl);
3745          tit; tit = dfs_cache_get_next_tgt(&tl, tit)) {
3746         rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->leaf_fullpath + 1, tit);
3747         if (!rc) {
3748             rc = is_path_remote(mnt_ctx);
3749             if (!rc || rc == -EREMOTE)
3750                 break;
3751         }
3752     }
3753 
3754 out:
3755     kfree(full_path);
3756     dfs_cache_free_tgts(&tl);
3757     return rc;
3758 }
3759 
3760 static int follow_dfs_link(struct mount_ctx *mnt_ctx)
3761 {
3762     int rc;
3763     struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3764     struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3765     char *full_path;
3766     int num_links = 0;
3767 
3768     full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3769     if (IS_ERR(full_path))
3770         return PTR_ERR(full_path);
3771 
3772     kfree(mnt_ctx->origin_fullpath);
3773     mnt_ctx->origin_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3774                                 cifs_remap(cifs_sb));
3775     kfree(full_path);
3776 
3777     if (IS_ERR(mnt_ctx->origin_fullpath)) {
3778         rc = PTR_ERR(mnt_ctx->origin_fullpath);
3779         mnt_ctx->origin_fullpath = NULL;
3780         return rc;
3781     }
3782 
3783     do {
3784         rc = __follow_dfs_link(mnt_ctx);
3785         if (!rc || rc != -EREMOTE)
3786             break;
3787     } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
3788 
3789     return rc;
3790 }
3791 
3792 /* Set up DFS referral paths for failover */
3793 static void setup_server_referral_paths(struct mount_ctx *mnt_ctx)
3794 {
3795     struct TCP_Server_Info *server = mnt_ctx->server;
3796 
3797     mutex_lock(&server->refpath_lock);
3798     server->origin_fullpath = mnt_ctx->origin_fullpath;
3799     server->leaf_fullpath = mnt_ctx->leaf_fullpath;
3800     server->current_fullpath = mnt_ctx->leaf_fullpath;
3801     mutex_unlock(&server->refpath_lock);
3802     mnt_ctx->origin_fullpath = mnt_ctx->leaf_fullpath = NULL;
3803 }
3804 
3805 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3806 {
3807     int rc;
3808     struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3809     struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3810     bool isdfs;
3811 
3812     rc = is_dfs_mount(&mnt_ctx, &isdfs, &tl);
3813     if (rc)
3814         goto error;
3815     if (!isdfs)
3816         goto out;
3817 
3818     /* proceed as DFS mount */
3819     uuid_gen(&mnt_ctx.mount_id);
3820     rc = connect_dfs_root(&mnt_ctx, &tl);
3821     dfs_cache_free_tgts(&tl);
3822 
3823     if (rc)
3824         goto error;
3825 
3826     rc = is_path_remote(&mnt_ctx);
3827     if (rc)
3828         rc = follow_dfs_link(&mnt_ctx);
3829     if (rc)
3830         goto error;
3831 
3832     setup_server_referral_paths(&mnt_ctx);
3833     /*
3834      * After reconnecting to a different server, unique ids won't match anymore, so we disable
3835      * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3836      */
3837     cifs_autodisable_serverino(cifs_sb);
3838     /*
3839      * Force the use of prefix path to support failover on DFS paths that resolve to targets
3840      * that have different prefix paths.
3841      */
3842     cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3843     kfree(cifs_sb->prepath);
3844     cifs_sb->prepath = ctx->prepath;
3845     ctx->prepath = NULL;
3846     uuid_copy(&cifs_sb->dfs_mount_id, &mnt_ctx.mount_id);
3847 
3848 out:
3849     free_xid(mnt_ctx.xid);
3850     cifs_try_adding_channels(cifs_sb, mnt_ctx.ses);
3851     return mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3852 
3853 error:
3854     dfs_cache_put_refsrv_sessions(&mnt_ctx.mount_id);
3855     kfree(mnt_ctx.origin_fullpath);
3856     kfree(mnt_ctx.leaf_fullpath);
3857     mount_put_conns(&mnt_ctx);
3858     return rc;
3859 }
3860 #else
3861 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3862 {
3863     int rc = 0;
3864     struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3865 
3866     rc = mount_get_conns(&mnt_ctx);
3867     if (rc)
3868         goto error;
3869 
3870     if (mnt_ctx.tcon) {
3871         rc = is_path_remote(&mnt_ctx);
3872         if (rc == -EREMOTE)
3873             rc = -EOPNOTSUPP;
3874         if (rc)
3875             goto error;
3876     }
3877 
3878     free_xid(mnt_ctx.xid);
3879     return mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3880 
3881 error:
3882     mount_put_conns(&mnt_ctx);
3883     return rc;
3884 }
3885 #endif
3886 
3887 /*
3888  * Issue a TREE_CONNECT request.
3889  */
3890 int
3891 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3892      const char *tree, struct cifs_tcon *tcon,
3893      const struct nls_table *nls_codepage)
3894 {
3895     struct smb_hdr *smb_buffer;
3896     struct smb_hdr *smb_buffer_response;
3897     TCONX_REQ *pSMB;
3898     TCONX_RSP *pSMBr;
3899     unsigned char *bcc_ptr;
3900     int rc = 0;
3901     int length;
3902     __u16 bytes_left, count;
3903 
3904     if (ses == NULL)
3905         return -EIO;
3906 
3907     smb_buffer = cifs_buf_get();
3908     if (smb_buffer == NULL)
3909         return -ENOMEM;
3910 
3911     smb_buffer_response = smb_buffer;
3912 
3913     header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3914             NULL /*no tid */ , 4 /*wct */ );
3915 
3916     smb_buffer->Mid = get_next_mid(ses->server);
3917     smb_buffer->Uid = ses->Suid;
3918     pSMB = (TCONX_REQ *) smb_buffer;
3919     pSMBr = (TCONX_RSP *) smb_buffer_response;
3920 
3921     pSMB->AndXCommand = 0xFF;
3922     pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3923     bcc_ptr = &pSMB->Password[0];
3924     if (tcon->pipe || (ses->server->sec_mode & SECMODE_USER)) {
3925         pSMB->PasswordLength = cpu_to_le16(1);  /* minimum */
3926         *bcc_ptr = 0; /* password is null byte */
3927         bcc_ptr++;              /* skip password */
3928         /* already aligned so no need to do it below */
3929     }
3930 
3931     if (ses->server->sign)
3932         smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3933 
3934     if (ses->capabilities & CAP_STATUS32) {
3935         smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3936     }
3937     if (ses->capabilities & CAP_DFS) {
3938         smb_buffer->Flags2 |= SMBFLG2_DFS;
3939     }
3940     if (ses->capabilities & CAP_UNICODE) {
3941         smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3942         length =
3943             cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3944             6 /* max utf8 char length in bytes */ *
3945             (/* server len*/ + 256 /* share len */), nls_codepage);
3946         bcc_ptr += 2 * length;  /* convert num 16 bit words to bytes */
3947         bcc_ptr += 2;   /* skip trailing null */
3948     } else {        /* ASCII */
3949         strcpy(bcc_ptr, tree);
3950         bcc_ptr += strlen(tree) + 1;
3951     }
3952     strcpy(bcc_ptr, "?????");
3953     bcc_ptr += strlen("?????");
3954     bcc_ptr += 1;
3955     count = bcc_ptr - &pSMB->Password[0];
3956     be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3957     pSMB->ByteCount = cpu_to_le16(count);
3958 
3959     rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3960              0);
3961 
3962     /* above now done in SendReceive */
3963     if (rc == 0) {
3964         bool is_unicode;
3965 
3966         tcon->tid = smb_buffer_response->Tid;
3967         bcc_ptr = pByteArea(smb_buffer_response);
3968         bytes_left = get_bcc(smb_buffer_response);
3969         length = strnlen(bcc_ptr, bytes_left - 2);
3970         if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3971             is_unicode = true;
3972         else
3973             is_unicode = false;
3974 
3975 
3976         /* skip service field (NB: this field is always ASCII) */
3977         if (length == 3) {
3978             if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3979                 (bcc_ptr[2] == 'C')) {
3980                 cifs_dbg(FYI, "IPC connection\n");
3981                 tcon->ipc = true;
3982                 tcon->pipe = true;
3983             }
3984         } else if (length == 2) {
3985             if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3986                 /* the most common case */
3987                 cifs_dbg(FYI, "disk share connection\n");
3988             }
3989         }
3990         bcc_ptr += length + 1;
3991         bytes_left -= (length + 1);
3992         strscpy(tcon->treeName, tree, sizeof(tcon->treeName));
3993 
3994         /* mostly informational -- no need to fail on error here */
3995         kfree(tcon->nativeFileSystem);
3996         tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3997                               bytes_left, is_unicode,
3998                               nls_codepage);
3999 
4000         cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
4001 
4002         if ((smb_buffer_response->WordCount == 3) ||
4003              (smb_buffer_response->WordCount == 7))
4004             /* field is in same location */
4005             tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
4006         else
4007             tcon->Flags = 0;
4008         cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
4009     }
4010 
4011     cifs_buf_release(smb_buffer);
4012     return rc;
4013 }
4014 
4015 static void delayed_free(struct rcu_head *p)
4016 {
4017     struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
4018 
4019     unload_nls(cifs_sb->local_nls);
4020     smb3_cleanup_fs_context(cifs_sb->ctx);
4021     kfree(cifs_sb);
4022 }
4023 
4024 void
4025 cifs_umount(struct cifs_sb_info *cifs_sb)
4026 {
4027     struct rb_root *root = &cifs_sb->tlink_tree;
4028     struct rb_node *node;
4029     struct tcon_link *tlink;
4030 
4031     cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
4032 
4033     spin_lock(&cifs_sb->tlink_tree_lock);
4034     while ((node = rb_first(root))) {
4035         tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4036         cifs_get_tlink(tlink);
4037         clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4038         rb_erase(node, root);
4039 
4040         spin_unlock(&cifs_sb->tlink_tree_lock);
4041         cifs_put_tlink(tlink);
4042         spin_lock(&cifs_sb->tlink_tree_lock);
4043     }
4044     spin_unlock(&cifs_sb->tlink_tree_lock);
4045 
4046     kfree(cifs_sb->prepath);
4047 #ifdef CONFIG_CIFS_DFS_UPCALL
4048     dfs_cache_put_refsrv_sessions(&cifs_sb->dfs_mount_id);
4049 #endif
4050     call_rcu(&cifs_sb->rcu, delayed_free);
4051 }
4052 
4053 int
4054 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
4055             struct TCP_Server_Info *server)
4056 {
4057     int rc = 0;
4058 
4059     if (!server->ops->need_neg || !server->ops->negotiate)
4060         return -ENOSYS;
4061 
4062     /* only send once per connect */
4063     spin_lock(&server->srv_lock);
4064     if (!server->ops->need_neg(server) ||
4065         server->tcpStatus != CifsNeedNegotiate) {
4066         spin_unlock(&server->srv_lock);
4067         return 0;
4068     }
4069     server->tcpStatus = CifsInNegotiate;
4070     spin_unlock(&server->srv_lock);
4071 
4072     rc = server->ops->negotiate(xid, ses, server);
4073     if (rc == 0) {
4074         spin_lock(&server->srv_lock);
4075         if (server->tcpStatus == CifsInNegotiate)
4076             server->tcpStatus = CifsGood;
4077         else
4078             rc = -EHOSTDOWN;
4079         spin_unlock(&server->srv_lock);
4080     } else {
4081         spin_lock(&server->srv_lock);
4082         if (server->tcpStatus == CifsInNegotiate)
4083             server->tcpStatus = CifsNeedNegotiate;
4084         spin_unlock(&server->srv_lock);
4085     }
4086 
4087     return rc;
4088 }
4089 
4090 int
4091 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
4092            struct TCP_Server_Info *server,
4093            struct nls_table *nls_info)
4094 {
4095     int rc = -ENOSYS;
4096     struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
4097     struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
4098     bool is_binding = false;
4099 
4100     spin_lock(&ses->ses_lock);
4101     if (server->dstaddr.ss_family == AF_INET6)
4102         scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
4103     else
4104         scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
4105 
4106     if (ses->ses_status != SES_GOOD &&
4107         ses->ses_status != SES_NEW &&
4108         ses->ses_status != SES_NEED_RECON) {
4109         spin_unlock(&ses->ses_lock);
4110         return 0;
4111     }
4112 
4113     /* only send once per connect */
4114     spin_lock(&ses->chan_lock);
4115     if (CIFS_ALL_CHANS_GOOD(ses) ||
4116         cifs_chan_in_reconnect(ses, server)) {
4117         spin_unlock(&ses->chan_lock);
4118         spin_unlock(&ses->ses_lock);
4119         return 0;
4120     }
4121     is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
4122     cifs_chan_set_in_reconnect(ses, server);
4123     spin_unlock(&ses->chan_lock);
4124 
4125     if (!is_binding)
4126         ses->ses_status = SES_IN_SETUP;
4127     spin_unlock(&ses->ses_lock);
4128 
4129     if (!is_binding) {
4130         ses->capabilities = server->capabilities;
4131         if (!linuxExtEnabled)
4132             ses->capabilities &= (~server->vals->cap_unix);
4133 
4134         if (ses->auth_key.response) {
4135             cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
4136                  ses->auth_key.response);
4137             kfree(ses->auth_key.response);
4138             ses->auth_key.response = NULL;
4139             ses->auth_key.len = 0;
4140         }
4141     }
4142 
4143     cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
4144          server->sec_mode, server->capabilities, server->timeAdj);
4145 
4146     if (server->ops->sess_setup)
4147         rc = server->ops->sess_setup(xid, ses, server, nls_info);
4148 
4149     if (rc) {
4150         cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
4151         spin_lock(&ses->ses_lock);
4152         if (ses->ses_status == SES_IN_SETUP)
4153             ses->ses_status = SES_NEED_RECON;
4154         spin_lock(&ses->chan_lock);
4155         cifs_chan_clear_in_reconnect(ses, server);
4156         spin_unlock(&ses->chan_lock);
4157         spin_unlock(&ses->ses_lock);
4158     } else {
4159         spin_lock(&ses->ses_lock);
4160         if (ses->ses_status == SES_IN_SETUP)
4161             ses->ses_status = SES_GOOD;
4162         spin_lock(&ses->chan_lock);
4163         cifs_chan_clear_in_reconnect(ses, server);
4164         cifs_chan_clear_need_reconnect(ses, server);
4165         spin_unlock(&ses->chan_lock);
4166         spin_unlock(&ses->ses_lock);
4167     }
4168 
4169     return rc;
4170 }
4171 
4172 static int
4173 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
4174 {
4175     ctx->sectype = ses->sectype;
4176 
4177     /* krb5 is special, since we don't need username or pw */
4178     if (ctx->sectype == Kerberos)
4179         return 0;
4180 
4181     return cifs_set_cifscreds(ctx, ses);
4182 }
4183 
4184 static struct cifs_tcon *
4185 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4186 {
4187     int rc;
4188     struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
4189     struct cifs_ses *ses;
4190     struct cifs_tcon *tcon = NULL;
4191     struct smb3_fs_context *ctx;
4192 
4193     ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
4194     if (ctx == NULL)
4195         return ERR_PTR(-ENOMEM);
4196 
4197     ctx->local_nls = cifs_sb->local_nls;
4198     ctx->linux_uid = fsuid;
4199     ctx->cred_uid = fsuid;
4200     ctx->UNC = master_tcon->treeName;
4201     ctx->retry = master_tcon->retry;
4202     ctx->nocase = master_tcon->nocase;
4203     ctx->nohandlecache = master_tcon->nohandlecache;
4204     ctx->local_lease = master_tcon->local_lease;
4205     ctx->no_lease = master_tcon->no_lease;
4206     ctx->resilient = master_tcon->use_resilient;
4207     ctx->persistent = master_tcon->use_persistent;
4208     ctx->handle_timeout = master_tcon->handle_timeout;
4209     ctx->no_linux_ext = !master_tcon->unix_ext;
4210     ctx->linux_ext = master_tcon->posix_extensions;
4211     ctx->sectype = master_tcon->ses->sectype;
4212     ctx->sign = master_tcon->ses->sign;
4213     ctx->seal = master_tcon->seal;
4214     ctx->witness = master_tcon->use_witness;
4215 
4216     rc = cifs_set_vol_auth(ctx, master_tcon->ses);
4217     if (rc) {
4218         tcon = ERR_PTR(rc);
4219         goto out;
4220     }
4221 
4222     /* get a reference for the same TCP session */
4223     spin_lock(&cifs_tcp_ses_lock);
4224     ++master_tcon->ses->server->srv_count;
4225     spin_unlock(&cifs_tcp_ses_lock);
4226 
4227     ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4228     if (IS_ERR(ses)) {
4229         tcon = (struct cifs_tcon *)ses;
4230         cifs_put_tcp_session(master_tcon->ses->server, 0);
4231         goto out;
4232     }
4233 
4234     tcon = cifs_get_tcon(ses, ctx);
4235     if (IS_ERR(tcon)) {
4236         cifs_put_smb_ses(ses);
4237         goto out;
4238     }
4239 
4240 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4241     if (cap_unix(ses))
4242         reset_cifs_unix_caps(0, tcon, NULL, ctx);
4243 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4244 
4245 out:
4246     kfree(ctx->username);
4247     kfree_sensitive(ctx->password);
4248     kfree(ctx);
4249 
4250     return tcon;
4251 }
4252 
4253 struct cifs_tcon *
4254 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4255 {
4256     return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4257 }
4258 
4259 /* find and return a tlink with given uid */
4260 static struct tcon_link *
4261 tlink_rb_search(struct rb_root *root, kuid_t uid)
4262 {
4263     struct rb_node *node = root->rb_node;
4264     struct tcon_link *tlink;
4265 
4266     while (node) {
4267         tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4268 
4269         if (uid_gt(tlink->tl_uid, uid))
4270             node = node->rb_left;
4271         else if (uid_lt(tlink->tl_uid, uid))
4272             node = node->rb_right;
4273         else
4274             return tlink;
4275     }
4276     return NULL;
4277 }
4278 
4279 /* insert a tcon_link into the tree */
4280 static void
4281 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4282 {
4283     struct rb_node **new = &(root->rb_node), *parent = NULL;
4284     struct tcon_link *tlink;
4285 
4286     while (*new) {
4287         tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4288         parent = *new;
4289 
4290         if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4291             new = &((*new)->rb_left);
4292         else
4293             new = &((*new)->rb_right);
4294     }
4295 
4296     rb_link_node(&new_tlink->tl_rbnode, parent, new);
4297     rb_insert_color(&new_tlink->tl_rbnode, root);
4298 }
4299 
4300 /*
4301  * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4302  * current task.
4303  *
4304  * If the superblock doesn't refer to a multiuser mount, then just return
4305  * the master tcon for the mount.
4306  *
4307  * First, search the rbtree for an existing tcon for this fsuid. If one
4308  * exists, then check to see if it's pending construction. If it is then wait
4309  * for construction to complete. Once it's no longer pending, check to see if
4310  * it failed and either return an error or retry construction, depending on
4311  * the timeout.
4312  *
4313  * If one doesn't exist then insert a new tcon_link struct into the tree and
4314  * try to construct a new one.
4315  */
4316 struct tcon_link *
4317 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4318 {
4319     int ret;
4320     kuid_t fsuid = current_fsuid();
4321     struct tcon_link *tlink, *newtlink;
4322 
4323     if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4324         return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4325 
4326     spin_lock(&cifs_sb->tlink_tree_lock);
4327     tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4328     if (tlink)
4329         cifs_get_tlink(tlink);
4330     spin_unlock(&cifs_sb->tlink_tree_lock);
4331 
4332     if (tlink == NULL) {
4333         newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4334         if (newtlink == NULL)
4335             return ERR_PTR(-ENOMEM);
4336         newtlink->tl_uid = fsuid;
4337         newtlink->tl_tcon = ERR_PTR(-EACCES);
4338         set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4339         set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4340         cifs_get_tlink(newtlink);
4341 
4342         spin_lock(&cifs_sb->tlink_tree_lock);
4343         /* was one inserted after previous search? */
4344         tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4345         if (tlink) {
4346             cifs_get_tlink(tlink);
4347             spin_unlock(&cifs_sb->tlink_tree_lock);
4348             kfree(newtlink);
4349             goto wait_for_construction;
4350         }
4351         tlink = newtlink;
4352         tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4353         spin_unlock(&cifs_sb->tlink_tree_lock);
4354     } else {
4355 wait_for_construction:
4356         ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4357                   TASK_INTERRUPTIBLE);
4358         if (ret) {
4359             cifs_put_tlink(tlink);
4360             return ERR_PTR(-ERESTARTSYS);
4361         }
4362 
4363         /* if it's good, return it */
4364         if (!IS_ERR(tlink->tl_tcon))
4365             return tlink;
4366 
4367         /* return error if we tried this already recently */
4368         if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4369             cifs_put_tlink(tlink);
4370             return ERR_PTR(-EACCES);
4371         }
4372 
4373         if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4374             goto wait_for_construction;
4375     }
4376 
4377     tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4378     clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4379     wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4380 
4381     if (IS_ERR(tlink->tl_tcon)) {
4382         cifs_put_tlink(tlink);
4383         return ERR_PTR(-EACCES);
4384     }
4385 
4386     return tlink;
4387 }
4388 
4389 /*
4390  * periodic workqueue job that scans tcon_tree for a superblock and closes
4391  * out tcons.
4392  */
4393 static void
4394 cifs_prune_tlinks(struct work_struct *work)
4395 {
4396     struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4397                             prune_tlinks.work);
4398     struct rb_root *root = &cifs_sb->tlink_tree;
4399     struct rb_node *node;
4400     struct rb_node *tmp;
4401     struct tcon_link *tlink;
4402 
4403     /*
4404      * Because we drop the spinlock in the loop in order to put the tlink
4405      * it's not guarded against removal of links from the tree. The only
4406      * places that remove entries from the tree are this function and
4407      * umounts. Because this function is non-reentrant and is canceled
4408      * before umount can proceed, this is safe.
4409      */
4410     spin_lock(&cifs_sb->tlink_tree_lock);
4411     node = rb_first(root);
4412     while (node != NULL) {
4413         tmp = node;
4414         node = rb_next(tmp);
4415         tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4416 
4417         if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4418             atomic_read(&tlink->tl_count) != 0 ||
4419             time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4420             continue;
4421 
4422         cifs_get_tlink(tlink);
4423         clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4424         rb_erase(tmp, root);
4425 
4426         spin_unlock(&cifs_sb->tlink_tree_lock);
4427         cifs_put_tlink(tlink);
4428         spin_lock(&cifs_sb->tlink_tree_lock);
4429     }
4430     spin_unlock(&cifs_sb->tlink_tree_lock);
4431 
4432     queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4433                 TLINK_IDLE_EXPIRE);
4434 }
4435 
4436 #ifdef CONFIG_CIFS_DFS_UPCALL
4437 /* Update dfs referral path of superblock */
4438 static int update_server_fullpath(struct TCP_Server_Info *server, struct cifs_sb_info *cifs_sb,
4439                   const char *target)
4440 {
4441     int rc = 0;
4442     size_t len = strlen(target);
4443     char *refpath, *npath;
4444 
4445     if (unlikely(len < 2 || *target != '\\'))
4446         return -EINVAL;
4447 
4448     if (target[1] == '\\') {
4449         len += 1;
4450         refpath = kmalloc(len, GFP_KERNEL);
4451         if (!refpath)
4452             return -ENOMEM;
4453 
4454         scnprintf(refpath, len, "%s", target);
4455     } else {
4456         len += sizeof("\\");
4457         refpath = kmalloc(len, GFP_KERNEL);
4458         if (!refpath)
4459             return -ENOMEM;
4460 
4461         scnprintf(refpath, len, "\\%s", target);
4462     }
4463 
4464     npath = dfs_cache_canonical_path(refpath, cifs_sb->local_nls, cifs_remap(cifs_sb));
4465     kfree(refpath);
4466 
4467     if (IS_ERR(npath)) {
4468         rc = PTR_ERR(npath);
4469     } else {
4470         mutex_lock(&server->refpath_lock);
4471         kfree(server->leaf_fullpath);
4472         server->leaf_fullpath = npath;
4473         mutex_unlock(&server->refpath_lock);
4474         server->current_fullpath = server->leaf_fullpath;
4475     }
4476     return rc;
4477 }
4478 
4479 static int target_share_matches_server(struct TCP_Server_Info *server, const char *tcp_host,
4480                        size_t tcp_host_len, char *share, bool *target_match)
4481 {
4482     int rc = 0;
4483     const char *dfs_host;
4484     size_t dfs_host_len;
4485 
4486     *target_match = true;
4487     extract_unc_hostname(share, &dfs_host, &dfs_host_len);
4488 
4489     /* Check if hostnames or addresses match */
4490     if (dfs_host_len != tcp_host_len || strncasecmp(dfs_host, tcp_host, dfs_host_len) != 0) {
4491         cifs_dbg(FYI, "%s: %.*s doesn't match %.*s\n", __func__, (int)dfs_host_len,
4492              dfs_host, (int)tcp_host_len, tcp_host);
4493         rc = match_target_ip(server, dfs_host, dfs_host_len, target_match);
4494         if (rc)
4495             cifs_dbg(VFS, "%s: failed to match target ip: %d\n", __func__, rc);
4496     }
4497     return rc;
4498 }
4499 
4500 static int __tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4501                      struct cifs_sb_info *cifs_sb, char *tree, bool islink,
4502                      struct dfs_cache_tgt_list *tl)
4503 {
4504     int rc;
4505     struct TCP_Server_Info *server = tcon->ses->server;
4506     const struct smb_version_operations *ops = server->ops;
4507     struct cifs_tcon *ipc = tcon->ses->tcon_ipc;
4508     char *share = NULL, *prefix = NULL;
4509     const char *tcp_host;
4510     size_t tcp_host_len;
4511     struct dfs_cache_tgt_iterator *tit;
4512     bool target_match;
4513 
4514     extract_unc_hostname(server->hostname, &tcp_host, &tcp_host_len);
4515 
4516     tit = dfs_cache_get_tgt_iterator(tl);
4517     if (!tit) {
4518         rc = -ENOENT;
4519         goto out;
4520     }
4521 
4522     /* Try to tree connect to all dfs targets */
4523     for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
4524         const char *target = dfs_cache_get_tgt_name(tit);
4525         struct dfs_cache_tgt_list ntl = DFS_CACHE_TGT_LIST_INIT(ntl);
4526 
4527         kfree(share);
4528         kfree(prefix);
4529         share = prefix = NULL;
4530 
4531         /* Check if share matches with tcp ses */
4532         rc = dfs_cache_get_tgt_share(server->current_fullpath + 1, tit, &share, &prefix);
4533         if (rc) {
4534             cifs_dbg(VFS, "%s: failed to parse target share: %d\n", __func__, rc);
4535             break;
4536         }
4537 
4538         rc = target_share_matches_server(server, tcp_host, tcp_host_len, share,
4539                          &target_match);
4540         if (rc)
4541             break;
4542         if (!target_match) {
4543             rc = -EHOSTUNREACH;
4544             continue;
4545         }
4546 
4547         if (ipc->need_reconnect) {
4548             scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4549             rc = ops->tree_connect(xid, ipc->ses, tree, ipc, cifs_sb->local_nls);
4550             if (rc)
4551                 break;
4552         }
4553 
4554         scnprintf(tree, MAX_TREE_SIZE, "\\%s", share);
4555         if (!islink) {
4556             rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4557             break;
4558         }
4559         /*
4560          * If no dfs referrals were returned from link target, then just do a TREE_CONNECT
4561          * to it.  Otherwise, cache the dfs referral and then mark current tcp ses for
4562          * reconnect so either the demultiplex thread or the echo worker will reconnect to
4563          * newly resolved target.
4564          */
4565         if (dfs_cache_find(xid, tcon->ses, cifs_sb->local_nls, cifs_remap(cifs_sb), target,
4566                    NULL, &ntl)) {
4567             rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4568             if (rc)
4569                 continue;
4570             rc = dfs_cache_noreq_update_tgthint(server->current_fullpath + 1, tit);
4571             if (!rc)
4572                 rc = cifs_update_super_prepath(cifs_sb, prefix);
4573         } else {
4574             /* Target is another dfs share */
4575             rc = update_server_fullpath(server, cifs_sb, target);
4576             dfs_cache_free_tgts(tl);
4577 
4578             if (!rc) {
4579                 rc = -EREMOTE;
4580                 list_replace_init(&ntl.tl_list, &tl->tl_list);
4581             } else
4582                 dfs_cache_free_tgts(&ntl);
4583         }
4584         break;
4585     }
4586 
4587 out:
4588     kfree(share);
4589     kfree(prefix);
4590 
4591     return rc;
4592 }
4593 
4594 static int tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4595                    struct cifs_sb_info *cifs_sb, char *tree, bool islink,
4596                    struct dfs_cache_tgt_list *tl)
4597 {
4598     int rc;
4599     int num_links = 0;
4600     struct TCP_Server_Info *server = tcon->ses->server;
4601 
4602     do {
4603         rc = __tree_connect_dfs_target(xid, tcon, cifs_sb, tree, islink, tl);
4604         if (!rc || rc != -EREMOTE)
4605             break;
4606     } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
4607     /*
4608      * If we couldn't tree connect to any targets from last referral path, then retry from
4609      * original referral path.
4610      */
4611     if (rc && server->current_fullpath != server->origin_fullpath) {
4612         server->current_fullpath = server->origin_fullpath;
4613         cifs_signal_cifsd_for_reconnect(server, true);
4614     }
4615 
4616     dfs_cache_free_tgts(tl);
4617     return rc;
4618 }
4619 
4620 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4621 {
4622     int rc;
4623     struct TCP_Server_Info *server = tcon->ses->server;
4624     const struct smb_version_operations *ops = server->ops;
4625     struct super_block *sb = NULL;
4626     struct cifs_sb_info *cifs_sb;
4627     struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
4628     char *tree;
4629     struct dfs_info3_param ref = {0};
4630 
4631     /* only send once per connect */
4632     spin_lock(&tcon->tc_lock);
4633     if (tcon->ses->ses_status != SES_GOOD ||
4634         (tcon->status != TID_NEW &&
4635         tcon->status != TID_NEED_TCON)) {
4636         spin_unlock(&tcon->tc_lock);
4637         return 0;
4638     }
4639     tcon->status = TID_IN_TCON;
4640     spin_unlock(&tcon->tc_lock);
4641 
4642     tree = kzalloc(MAX_TREE_SIZE, GFP_KERNEL);
4643     if (!tree) {
4644         rc = -ENOMEM;
4645         goto out;
4646     }
4647 
4648     if (tcon->ipc) {
4649         scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4650         rc = ops->tree_connect(xid, tcon->ses, tree, tcon, nlsc);
4651         goto out;
4652     }
4653 
4654     sb = cifs_get_tcp_super(server);
4655     if (IS_ERR(sb)) {
4656         rc = PTR_ERR(sb);
4657         cifs_dbg(VFS, "%s: could not find superblock: %d\n", __func__, rc);
4658         goto out;
4659     }
4660 
4661     cifs_sb = CIFS_SB(sb);
4662 
4663     /* If it is not dfs or there was no cached dfs referral, then reconnect to same share */
4664     if (!server->current_fullpath ||
4665         dfs_cache_noreq_find(server->current_fullpath + 1, &ref, &tl)) {
4666         rc = ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, cifs_sb->local_nls);
4667         goto out;
4668     }
4669 
4670     rc = tree_connect_dfs_target(xid, tcon, cifs_sb, tree, ref.server_type == DFS_TYPE_LINK,
4671                      &tl);
4672     free_dfs_info_param(&ref);
4673 
4674 out:
4675     kfree(tree);
4676     cifs_put_tcp_super(sb);
4677 
4678     if (rc) {
4679         spin_lock(&tcon->tc_lock);
4680         if (tcon->status == TID_IN_TCON)
4681             tcon->status = TID_NEED_TCON;
4682         spin_unlock(&tcon->tc_lock);
4683     } else {
4684         spin_lock(&tcon->tc_lock);
4685         if (tcon->status == TID_IN_TCON)
4686             tcon->status = TID_GOOD;
4687         spin_unlock(&tcon->tc_lock);
4688         tcon->need_reconnect = false;
4689     }
4690 
4691     return rc;
4692 }
4693 #else
4694 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4695 {
4696     int rc;
4697     const struct smb_version_operations *ops = tcon->ses->server->ops;
4698 
4699     /* only send once per connect */
4700     spin_lock(&tcon->tc_lock);
4701     if (tcon->ses->ses_status != SES_GOOD ||
4702         (tcon->status != TID_NEW &&
4703         tcon->status != TID_NEED_TCON)) {
4704         spin_unlock(&tcon->tc_lock);
4705         return 0;
4706     }
4707     tcon->status = TID_IN_TCON;
4708     spin_unlock(&tcon->tc_lock);
4709 
4710     rc = ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, nlsc);
4711     if (rc) {
4712         spin_lock(&tcon->tc_lock);
4713         if (tcon->status == TID_IN_TCON)
4714             tcon->status = TID_NEED_TCON;
4715         spin_unlock(&tcon->tc_lock);
4716     } else {
4717         spin_lock(&tcon->tc_lock);
4718         if (tcon->status == TID_IN_TCON)
4719             tcon->status = TID_GOOD;
4720         tcon->need_reconnect = false;
4721         spin_unlock(&tcon->tc_lock);
4722     }
4723 
4724     return rc;
4725 }
4726 #endif