smb: client: Fix minor whitespace errors and warnings
[linux-modified.git] / fs / smb / client / connect.c
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2011
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  */
8 #include <linux/fs.h>
9 #include <linux/net.h>
10 #include <linux/string.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/signal.h>
13 #include <linux/list.h>
14 #include <linux/wait.h>
15 #include <linux/slab.h>
16 #include <linux/pagemap.h>
17 #include <linux/ctype.h>
18 #include <linux/utsname.h>
19 #include <linux/mempool.h>
20 #include <linux/delay.h>
21 #include <linux/completion.h>
22 #include <linux/kthread.h>
23 #include <linux/pagevec.h>
24 #include <linux/freezer.h>
25 #include <linux/namei.h>
26 #include <linux/uuid.h>
27 #include <linux/uaccess.h>
28 #include <asm/processor.h>
29 #include <linux/inet.h>
30 #include <linux/module.h>
31 #include <keys/user-type.h>
32 #include <net/ipv6.h>
33 #include <linux/parser.h>
34 #include <linux/bvec.h>
35 #include "cifspdu.h"
36 #include "cifsglob.h"
37 #include "cifsproto.h"
38 #include "cifs_unicode.h"
39 #include "cifs_debug.h"
40 #include "cifs_fs_sb.h"
41 #include "ntlmssp.h"
42 #include "nterr.h"
43 #include "rfc1002pdu.h"
44 #include "fscache.h"
45 #include "smb2proto.h"
46 #include "smbdirect.h"
47 #include "dns_resolve.h"
48 #ifdef CONFIG_CIFS_DFS_UPCALL
49 #include "dfs.h"
50 #include "dfs_cache.h"
51 #endif
52 #include "fs_context.h"
53 #include "cifs_swn.h"
54
55 extern mempool_t *cifs_req_poolp;
56 extern bool disable_legacy_dialects;
57
58 /* FIXME: should these be tunable? */
59 #define TLINK_ERROR_EXPIRE      (1 * HZ)
60 #define TLINK_IDLE_EXPIRE       (600 * HZ)
61
62 /* Drop the connection to not overload the server */
63 #define MAX_STATUS_IO_TIMEOUT   5
64
65 static int ip_connect(struct TCP_Server_Info *server);
66 static int generic_ip_connect(struct TCP_Server_Info *server);
67 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
68 static void cifs_prune_tlinks(struct work_struct *work);
69
70 /*
71  * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
72  * get their ip addresses changed at some point.
73  *
74  * This should be called with server->srv_mutex held.
75  */
76 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
77 {
78         int rc;
79         int len;
80         char *unc;
81         struct sockaddr_storage ss;
82
83         if (!server->hostname)
84                 return -EINVAL;
85
86         /* if server hostname isn't populated, there's nothing to do here */
87         if (server->hostname[0] == '\0')
88                 return 0;
89
90         len = strlen(server->hostname) + 3;
91
92         unc = kmalloc(len, GFP_KERNEL);
93         if (!unc) {
94                 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
95                 return -ENOMEM;
96         }
97         scnprintf(unc, len, "\\\\%s", server->hostname);
98
99         spin_lock(&server->srv_lock);
100         ss = server->dstaddr;
101         spin_unlock(&server->srv_lock);
102
103         rc = dns_resolve_server_name_to_ip(unc, (struct sockaddr *)&ss, NULL);
104         kfree(unc);
105
106         if (rc < 0) {
107                 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
108                          __func__, server->hostname, rc);
109         } else {
110                 spin_lock(&server->srv_lock);
111                 memcpy(&server->dstaddr, &ss, sizeof(server->dstaddr));
112                 spin_unlock(&server->srv_lock);
113                 rc = 0;
114         }
115
116         return rc;
117 }
118
119 static void smb2_query_server_interfaces(struct work_struct *work)
120 {
121         int rc;
122         int xid;
123         struct cifs_tcon *tcon = container_of(work,
124                                         struct cifs_tcon,
125                                         query_interfaces.work);
126
127         /*
128          * query server network interfaces, in case they change
129          */
130         xid = get_xid();
131         rc = SMB3_request_interfaces(xid, tcon, false);
132         free_xid(xid);
133
134         if (rc) {
135                 if (rc == -EOPNOTSUPP)
136                         return;
137
138                 cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
139                                 __func__, rc);
140         }
141
142         queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
143                            (SMB_INTERFACE_POLL_INTERVAL * HZ));
144 }
145
146 /*
147  * Update the tcpStatus for the server.
148  * This is used to signal the cifsd thread to call cifs_reconnect
149  * ONLY cifsd thread should call cifs_reconnect. For any other
150  * thread, use this function
151  *
152  * @server: the tcp ses for which reconnect is needed
153  * @all_channels: if this needs to be done for all channels
154  */
155 void
156 cifs_signal_cifsd_for_reconnect(struct TCP_Server_Info *server,
157                                 bool all_channels)
158 {
159         struct TCP_Server_Info *pserver;
160         struct cifs_ses *ses;
161         int i;
162
163         /* If server is a channel, select the primary channel */
164         pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
165
166         /* if we need to signal just this channel */
167         if (!all_channels) {
168                 spin_lock(&server->srv_lock);
169                 if (server->tcpStatus != CifsExiting)
170                         server->tcpStatus = CifsNeedReconnect;
171                 spin_unlock(&server->srv_lock);
172                 return;
173         }
174
175         spin_lock(&cifs_tcp_ses_lock);
176         list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
177                 spin_lock(&ses->chan_lock);
178                 for (i = 0; i < ses->chan_count; i++) {
179                         if (!ses->chans[i].server)
180                                 continue;
181
182                         spin_lock(&ses->chans[i].server->srv_lock);
183                         if (ses->chans[i].server->tcpStatus != CifsExiting)
184                                 ses->chans[i].server->tcpStatus = CifsNeedReconnect;
185                         spin_unlock(&ses->chans[i].server->srv_lock);
186                 }
187                 spin_unlock(&ses->chan_lock);
188         }
189         spin_unlock(&cifs_tcp_ses_lock);
190 }
191
192 /*
193  * Mark all sessions and tcons for reconnect.
194  * IMPORTANT: make sure that this gets called only from
195  * cifsd thread. For any other thread, use
196  * cifs_signal_cifsd_for_reconnect
197  *
198  * @server: the tcp ses for which reconnect is needed
199  * @server needs to be previously set to CifsNeedReconnect.
200  * @mark_smb_session: whether even sessions need to be marked
201  */
202 void
203 cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server,
204                                       bool mark_smb_session)
205 {
206         struct TCP_Server_Info *pserver;
207         struct cifs_ses *ses, *nses;
208         struct cifs_tcon *tcon;
209
210         /*
211          * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
212          * are not used until reconnected.
213          */
214         cifs_dbg(FYI, "%s: marking necessary sessions and tcons for reconnect\n", __func__);
215
216         /* If server is a channel, select the primary channel */
217         pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
218
219
220         spin_lock(&cifs_tcp_ses_lock);
221         list_for_each_entry_safe(ses, nses, &pserver->smb_ses_list, smb_ses_list) {
222                 /*
223                  * if channel has been marked for termination, nothing to do
224                  * for the channel. in fact, we cannot find the channel for the
225                  * server. So safe to exit here
226                  */
227                 if (server->terminate)
228                         break;
229
230                 /* check if iface is still active */
231                 if (!cifs_chan_is_iface_active(ses, server))
232                         cifs_chan_update_iface(ses, server);
233
234                 spin_lock(&ses->chan_lock);
235                 if (!mark_smb_session && cifs_chan_needs_reconnect(ses, server)) {
236                         spin_unlock(&ses->chan_lock);
237                         continue;
238                 }
239
240                 if (mark_smb_session)
241                         CIFS_SET_ALL_CHANS_NEED_RECONNECT(ses);
242                 else
243                         cifs_chan_set_need_reconnect(ses, server);
244
245                 cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
246                          __func__, ses->chans_need_reconnect);
247
248                 /* If all channels need reconnect, then tcon needs reconnect */
249                 if (!mark_smb_session && !CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
250                         spin_unlock(&ses->chan_lock);
251                         continue;
252                 }
253                 spin_unlock(&ses->chan_lock);
254
255                 spin_lock(&ses->ses_lock);
256                 ses->ses_status = SES_NEED_RECON;
257                 spin_unlock(&ses->ses_lock);
258
259                 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
260                         tcon->need_reconnect = true;
261                         spin_lock(&tcon->tc_lock);
262                         tcon->status = TID_NEED_RECON;
263                         spin_unlock(&tcon->tc_lock);
264
265                         cancel_delayed_work(&tcon->query_interfaces);
266                 }
267                 if (ses->tcon_ipc) {
268                         ses->tcon_ipc->need_reconnect = true;
269                         spin_lock(&ses->tcon_ipc->tc_lock);
270                         ses->tcon_ipc->status = TID_NEED_RECON;
271                         spin_unlock(&ses->tcon_ipc->tc_lock);
272                 }
273         }
274         spin_unlock(&cifs_tcp_ses_lock);
275 }
276
277 static void
278 cifs_abort_connection(struct TCP_Server_Info *server)
279 {
280         struct mid_q_entry *mid, *nmid;
281         struct list_head retry_list;
282
283         server->maxBuf = 0;
284         server->max_read = 0;
285
286         /* do not want to be sending data on a socket we are freeing */
287         cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
288         cifs_server_lock(server);
289         if (server->ssocket) {
290                 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
291                          server->ssocket->flags);
292                 kernel_sock_shutdown(server->ssocket, SHUT_WR);
293                 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
294                          server->ssocket->flags);
295                 sock_release(server->ssocket);
296                 server->ssocket = NULL;
297         }
298         server->sequence_number = 0;
299         server->session_estab = false;
300         kfree_sensitive(server->session_key.response);
301         server->session_key.response = NULL;
302         server->session_key.len = 0;
303         server->lstrp = jiffies;
304
305         /* mark submitted MIDs for retry and issue callback */
306         INIT_LIST_HEAD(&retry_list);
307         cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
308         spin_lock(&server->mid_lock);
309         list_for_each_entry_safe(mid, nmid, &server->pending_mid_q, qhead) {
310                 kref_get(&mid->refcount);
311                 if (mid->mid_state == MID_REQUEST_SUBMITTED)
312                         mid->mid_state = MID_RETRY_NEEDED;
313                 list_move(&mid->qhead, &retry_list);
314                 mid->mid_flags |= MID_DELETED;
315         }
316         spin_unlock(&server->mid_lock);
317         cifs_server_unlock(server);
318
319         cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
320         list_for_each_entry_safe(mid, nmid, &retry_list, qhead) {
321                 list_del_init(&mid->qhead);
322                 mid->callback(mid);
323                 release_mid(mid);
324         }
325
326         if (cifs_rdma_enabled(server)) {
327                 cifs_server_lock(server);
328                 smbd_destroy(server);
329                 cifs_server_unlock(server);
330         }
331 }
332
333 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
334 {
335         spin_lock(&server->srv_lock);
336         server->nr_targets = num_targets;
337         if (server->tcpStatus == CifsExiting) {
338                 /* the demux thread will exit normally next time through the loop */
339                 spin_unlock(&server->srv_lock);
340                 wake_up(&server->response_q);
341                 return false;
342         }
343
344         cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
345         trace_smb3_reconnect(server->CurrentMid, server->conn_id,
346                              server->hostname);
347         server->tcpStatus = CifsNeedReconnect;
348
349         spin_unlock(&server->srv_lock);
350         return true;
351 }
352
353 /*
354  * cifs tcp session reconnection
355  *
356  * mark tcp session as reconnecting so temporarily locked
357  * mark all smb sessions as reconnecting for tcp session
358  * reconnect tcp session
359  * wake up waiters on reconnection? - (not needed currently)
360  *
361  * if mark_smb_session is passed as true, unconditionally mark
362  * the smb session (and tcon) for reconnect as well. This value
363  * doesn't really matter for non-multichannel scenario.
364  *
365  */
366 static int __cifs_reconnect(struct TCP_Server_Info *server,
367                             bool mark_smb_session)
368 {
369         int rc = 0;
370
371         if (!cifs_tcp_ses_needs_reconnect(server, 1))
372                 return 0;
373
374         cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
375
376         cifs_abort_connection(server);
377
378         do {
379                 try_to_freeze();
380                 cifs_server_lock(server);
381
382                 if (!cifs_swn_set_server_dstaddr(server)) {
383                         /* resolve the hostname again to make sure that IP address is up-to-date */
384                         rc = reconn_set_ipaddr_from_hostname(server);
385                         cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
386                 }
387
388                 if (cifs_rdma_enabled(server))
389                         rc = smbd_reconnect(server);
390                 else
391                         rc = generic_ip_connect(server);
392                 if (rc) {
393                         cifs_server_unlock(server);
394                         cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
395                         msleep(3000);
396                 } else {
397                         atomic_inc(&tcpSesReconnectCount);
398                         set_credits(server, 1);
399                         spin_lock(&server->srv_lock);
400                         if (server->tcpStatus != CifsExiting)
401                                 server->tcpStatus = CifsNeedNegotiate;
402                         spin_unlock(&server->srv_lock);
403                         cifs_swn_reset_server_dstaddr(server);
404                         cifs_server_unlock(server);
405                         mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
406                 }
407         } while (server->tcpStatus == CifsNeedReconnect);
408
409         spin_lock(&server->srv_lock);
410         if (server->tcpStatus == CifsNeedNegotiate)
411                 mod_delayed_work(cifsiod_wq, &server->echo, 0);
412         spin_unlock(&server->srv_lock);
413
414         wake_up(&server->response_q);
415         return rc;
416 }
417
418 #ifdef CONFIG_CIFS_DFS_UPCALL
419 static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
420 {
421         int rc;
422         char *hostname;
423
424         if (!cifs_swn_set_server_dstaddr(server)) {
425                 if (server->hostname != target) {
426                         hostname = extract_hostname(target);
427                         if (!IS_ERR(hostname)) {
428                                 spin_lock(&server->srv_lock);
429                                 kfree(server->hostname);
430                                 server->hostname = hostname;
431                                 spin_unlock(&server->srv_lock);
432                         } else {
433                                 cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
434                                          __func__, PTR_ERR(hostname));
435                                 cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
436                                          server->hostname);
437                         }
438                 }
439                 /* resolve the hostname again to make sure that IP address is up-to-date. */
440                 rc = reconn_set_ipaddr_from_hostname(server);
441                 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
442         }
443         /* Reconnect the socket */
444         if (cifs_rdma_enabled(server))
445                 rc = smbd_reconnect(server);
446         else
447                 rc = generic_ip_connect(server);
448
449         return rc;
450 }
451
452 static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
453                                      struct dfs_cache_tgt_iterator **target_hint)
454 {
455         int rc;
456         struct dfs_cache_tgt_iterator *tit;
457
458         *target_hint = NULL;
459
460         /* If dfs target list is empty, then reconnect to last server */
461         tit = dfs_cache_get_tgt_iterator(tl);
462         if (!tit)
463                 return __reconnect_target_unlocked(server, server->hostname);
464
465         /* Otherwise, try every dfs target in @tl */
466         for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
467                 rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
468                 if (!rc) {
469                         *target_hint = tit;
470                         break;
471                 }
472         }
473         return rc;
474 }
475
476 static int reconnect_dfs_server(struct TCP_Server_Info *server)
477 {
478         struct dfs_cache_tgt_iterator *target_hint = NULL;
479
480         DFS_CACHE_TGT_LIST(tl);
481         int num_targets = 0;
482         int rc = 0;
483
484         /*
485          * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
486          *
487          * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
488          * targets (server->nr_targets).  It's also possible that the cached referral was cleared
489          * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
490          * refreshing the referral, so, in this case, default it to 1.
491          */
492         mutex_lock(&server->refpath_lock);
493         if (!dfs_cache_noreq_find(server->leaf_fullpath + 1, NULL, &tl))
494                 num_targets = dfs_cache_get_nr_tgts(&tl);
495         mutex_unlock(&server->refpath_lock);
496         if (!num_targets)
497                 num_targets = 1;
498
499         if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
500                 return 0;
501
502         /*
503          * Unconditionally mark all sessions & tcons for reconnect as we might be connecting to a
504          * different server or share during failover.  It could be improved by adding some logic to
505          * only do that in case it connects to a different server or share, though.
506          */
507         cifs_mark_tcp_ses_conns_for_reconnect(server, true);
508
509         cifs_abort_connection(server);
510
511         do {
512                 try_to_freeze();
513                 cifs_server_lock(server);
514
515                 rc = reconnect_target_unlocked(server, &tl, &target_hint);
516                 if (rc) {
517                         /* Failed to reconnect socket */
518                         cifs_server_unlock(server);
519                         cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
520                         msleep(3000);
521                         continue;
522                 }
523                 /*
524                  * Socket was created.  Update tcp session status to CifsNeedNegotiate so that a
525                  * process waiting for reconnect will know it needs to re-establish session and tcon
526                  * through the reconnected target server.
527                  */
528                 atomic_inc(&tcpSesReconnectCount);
529                 set_credits(server, 1);
530                 spin_lock(&server->srv_lock);
531                 if (server->tcpStatus != CifsExiting)
532                         server->tcpStatus = CifsNeedNegotiate;
533                 spin_unlock(&server->srv_lock);
534                 cifs_swn_reset_server_dstaddr(server);
535                 cifs_server_unlock(server);
536                 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
537         } while (server->tcpStatus == CifsNeedReconnect);
538
539         mutex_lock(&server->refpath_lock);
540         dfs_cache_noreq_update_tgthint(server->leaf_fullpath + 1, target_hint);
541         mutex_unlock(&server->refpath_lock);
542         dfs_cache_free_tgts(&tl);
543
544         /* Need to set up echo worker again once connection has been established */
545         spin_lock(&server->srv_lock);
546         if (server->tcpStatus == CifsNeedNegotiate)
547                 mod_delayed_work(cifsiod_wq, &server->echo, 0);
548         spin_unlock(&server->srv_lock);
549
550         wake_up(&server->response_q);
551         return rc;
552 }
553
554 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
555 {
556         mutex_lock(&server->refpath_lock);
557         if (!server->leaf_fullpath) {
558                 mutex_unlock(&server->refpath_lock);
559                 return __cifs_reconnect(server, mark_smb_session);
560         }
561         mutex_unlock(&server->refpath_lock);
562
563         return reconnect_dfs_server(server);
564 }
565 #else
566 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
567 {
568         return __cifs_reconnect(server, mark_smb_session);
569 }
570 #endif
571
572 static void
573 cifs_echo_request(struct work_struct *work)
574 {
575         int rc;
576         struct TCP_Server_Info *server = container_of(work,
577                                         struct TCP_Server_Info, echo.work);
578
579         /*
580          * We cannot send an echo if it is disabled.
581          * Also, no need to ping if we got a response recently.
582          */
583
584         if (server->tcpStatus == CifsNeedReconnect ||
585             server->tcpStatus == CifsExiting ||
586             server->tcpStatus == CifsNew ||
587             (server->ops->can_echo && !server->ops->can_echo(server)) ||
588             time_before(jiffies, server->lstrp + server->echo_interval - HZ))
589                 goto requeue_echo;
590
591         rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
592         cifs_server_dbg(FYI, "send echo request: rc = %d\n", rc);
593
594         /* Check witness registrations */
595         cifs_swn_check();
596
597 requeue_echo:
598         queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
599 }
600
601 static bool
602 allocate_buffers(struct TCP_Server_Info *server)
603 {
604         if (!server->bigbuf) {
605                 server->bigbuf = (char *)cifs_buf_get();
606                 if (!server->bigbuf) {
607                         cifs_server_dbg(VFS, "No memory for large SMB response\n");
608                         msleep(3000);
609                         /* retry will check if exiting */
610                         return false;
611                 }
612         } else if (server->large_buf) {
613                 /* we are reusing a dirty large buf, clear its start */
614                 memset(server->bigbuf, 0, HEADER_SIZE(server));
615         }
616
617         if (!server->smallbuf) {
618                 server->smallbuf = (char *)cifs_small_buf_get();
619                 if (!server->smallbuf) {
620                         cifs_server_dbg(VFS, "No memory for SMB response\n");
621                         msleep(1000);
622                         /* retry will check if exiting */
623                         return false;
624                 }
625                 /* beginning of smb buffer is cleared in our buf_get */
626         } else {
627                 /* if existing small buf clear beginning */
628                 memset(server->smallbuf, 0, HEADER_SIZE(server));
629         }
630
631         return true;
632 }
633
634 static bool
635 server_unresponsive(struct TCP_Server_Info *server)
636 {
637         /*
638          * We need to wait 3 echo intervals to make sure we handle such
639          * situations right:
640          * 1s  client sends a normal SMB request
641          * 2s  client gets a response
642          * 30s echo workqueue job pops, and decides we got a response recently
643          *     and don't need to send another
644          * ...
645          * 65s kernel_recvmsg times out, and we see that we haven't gotten
646          *     a response in >60s.
647          */
648         spin_lock(&server->srv_lock);
649         if ((server->tcpStatus == CifsGood ||
650             server->tcpStatus == CifsNeedNegotiate) &&
651             (!server->ops->can_echo || server->ops->can_echo(server)) &&
652             time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
653                 spin_unlock(&server->srv_lock);
654                 cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
655                          (3 * server->echo_interval) / HZ);
656                 cifs_reconnect(server, false);
657                 return true;
658         }
659         spin_unlock(&server->srv_lock);
660
661         return false;
662 }
663
664 static inline bool
665 zero_credits(struct TCP_Server_Info *server)
666 {
667         int val;
668
669         spin_lock(&server->req_lock);
670         val = server->credits + server->echo_credits + server->oplock_credits;
671         if (server->in_flight == 0 && val == 0) {
672                 spin_unlock(&server->req_lock);
673                 return true;
674         }
675         spin_unlock(&server->req_lock);
676         return false;
677 }
678
679 static int
680 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
681 {
682         int length = 0;
683         int total_read;
684
685         for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
686                 try_to_freeze();
687
688                 /* reconnect if no credits and no requests in flight */
689                 if (zero_credits(server)) {
690                         cifs_reconnect(server, false);
691                         return -ECONNABORTED;
692                 }
693
694                 if (server_unresponsive(server))
695                         return -ECONNABORTED;
696                 if (cifs_rdma_enabled(server) && server->smbd_conn)
697                         length = smbd_recv(server->smbd_conn, smb_msg);
698                 else
699                         length = sock_recvmsg(server->ssocket, smb_msg, 0);
700
701                 spin_lock(&server->srv_lock);
702                 if (server->tcpStatus == CifsExiting) {
703                         spin_unlock(&server->srv_lock);
704                         return -ESHUTDOWN;
705                 }
706
707                 if (server->tcpStatus == CifsNeedReconnect) {
708                         spin_unlock(&server->srv_lock);
709                         cifs_reconnect(server, false);
710                         return -ECONNABORTED;
711                 }
712                 spin_unlock(&server->srv_lock);
713
714                 if (length == -ERESTARTSYS ||
715                     length == -EAGAIN ||
716                     length == -EINTR) {
717                         /*
718                          * Minimum sleep to prevent looping, allowing socket
719                          * to clear and app threads to set tcpStatus
720                          * CifsNeedReconnect if server hung.
721                          */
722                         usleep_range(1000, 2000);
723                         length = 0;
724                         continue;
725                 }
726
727                 if (length <= 0) {
728                         cifs_dbg(FYI, "Received no data or error: %d\n", length);
729                         cifs_reconnect(server, false);
730                         return -ECONNABORTED;
731                 }
732         }
733         return total_read;
734 }
735
736 int
737 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
738                       unsigned int to_read)
739 {
740         struct msghdr smb_msg = {};
741         struct kvec iov = {.iov_base = buf, .iov_len = to_read};
742
743         iov_iter_kvec(&smb_msg.msg_iter, ITER_DEST, &iov, 1, to_read);
744
745         return cifs_readv_from_socket(server, &smb_msg);
746 }
747
748 ssize_t
749 cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
750 {
751         struct msghdr smb_msg = {};
752
753         /*
754          *  iov_iter_discard already sets smb_msg.type and count and iov_offset
755          *  and cifs_readv_from_socket sets msg_control and msg_controllen
756          *  so little to initialize in struct msghdr
757          */
758         iov_iter_discard(&smb_msg.msg_iter, ITER_DEST, to_read);
759
760         return cifs_readv_from_socket(server, &smb_msg);
761 }
762
763 int
764 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
765         unsigned int page_offset, unsigned int to_read)
766 {
767         struct msghdr smb_msg = {};
768         struct bio_vec bv;
769
770         bvec_set_page(&bv, page, to_read, page_offset);
771         iov_iter_bvec(&smb_msg.msg_iter, ITER_DEST, &bv, 1, to_read);
772         return cifs_readv_from_socket(server, &smb_msg);
773 }
774
775 int
776 cifs_read_iter_from_socket(struct TCP_Server_Info *server, struct iov_iter *iter,
777                            unsigned int to_read)
778 {
779         struct msghdr smb_msg = { .msg_iter = *iter };
780         int ret;
781
782         iov_iter_truncate(&smb_msg.msg_iter, to_read);
783         ret = cifs_readv_from_socket(server, &smb_msg);
784         if (ret > 0)
785                 iov_iter_advance(iter, ret);
786         return ret;
787 }
788
789 static bool
790 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
791 {
792         /*
793          * The first byte big endian of the length field,
794          * is actually not part of the length but the type
795          * with the most common, zero, as regular data.
796          */
797         switch (type) {
798         case RFC1002_SESSION_MESSAGE:
799                 /* Regular SMB response */
800                 return true;
801         case RFC1002_SESSION_KEEP_ALIVE:
802                 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
803                 break;
804         case RFC1002_POSITIVE_SESSION_RESPONSE:
805                 cifs_dbg(FYI, "RFC 1002 positive session response\n");
806                 break;
807         case RFC1002_NEGATIVE_SESSION_RESPONSE:
808                 /*
809                  * We get this from Windows 98 instead of an error on
810                  * SMB negprot response.
811                  */
812                 cifs_dbg(FYI, "RFC 1002 negative session response\n");
813                 /* give server a second to clean up */
814                 msleep(1000);
815                 /*
816                  * Always try 445 first on reconnect since we get NACK
817                  * on some if we ever connected to port 139 (the NACK
818                  * is since we do not begin with RFC1001 session
819                  * initialize frame).
820                  */
821                 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
822                 cifs_reconnect(server, true);
823                 break;
824         default:
825                 cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
826                 cifs_reconnect(server, true);
827         }
828
829         return false;
830 }
831
832 void
833 dequeue_mid(struct mid_q_entry *mid, bool malformed)
834 {
835 #ifdef CONFIG_CIFS_STATS2
836         mid->when_received = jiffies;
837 #endif
838         spin_lock(&mid->server->mid_lock);
839         if (!malformed)
840                 mid->mid_state = MID_RESPONSE_RECEIVED;
841         else
842                 mid->mid_state = MID_RESPONSE_MALFORMED;
843         /*
844          * Trying to handle/dequeue a mid after the send_recv()
845          * function has finished processing it is a bug.
846          */
847         if (mid->mid_flags & MID_DELETED) {
848                 spin_unlock(&mid->server->mid_lock);
849                 pr_warn_once("trying to dequeue a deleted mid\n");
850         } else {
851                 list_del_init(&mid->qhead);
852                 mid->mid_flags |= MID_DELETED;
853                 spin_unlock(&mid->server->mid_lock);
854         }
855 }
856
857 static unsigned int
858 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
859 {
860         struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
861
862         /*
863          * SMB1 does not use credits.
864          */
865         if (is_smb1(server))
866                 return 0;
867
868         return le16_to_cpu(shdr->CreditRequest);
869 }
870
871 static void
872 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
873            char *buf, int malformed)
874 {
875         if (server->ops->check_trans2 &&
876             server->ops->check_trans2(mid, server, buf, malformed))
877                 return;
878         mid->credits_received = smb2_get_credits_from_hdr(buf, server);
879         mid->resp_buf = buf;
880         mid->large_buf = server->large_buf;
881         /* Was previous buf put in mpx struct for multi-rsp? */
882         if (!mid->multiRsp) {
883                 /* smb buffer will be freed by user thread */
884                 if (server->large_buf)
885                         server->bigbuf = NULL;
886                 else
887                         server->smallbuf = NULL;
888         }
889         dequeue_mid(mid, malformed);
890 }
891
892 int
893 cifs_enable_signing(struct TCP_Server_Info *server, bool mnt_sign_required)
894 {
895         bool srv_sign_required = server->sec_mode & server->vals->signing_required;
896         bool srv_sign_enabled = server->sec_mode & server->vals->signing_enabled;
897         bool mnt_sign_enabled;
898
899         /*
900          * Is signing required by mnt options? If not then check
901          * global_secflags to see if it is there.
902          */
903         if (!mnt_sign_required)
904                 mnt_sign_required = ((global_secflags & CIFSSEC_MUST_SIGN) ==
905                                                 CIFSSEC_MUST_SIGN);
906
907         /*
908          * If signing is required then it's automatically enabled too,
909          * otherwise, check to see if the secflags allow it.
910          */
911         mnt_sign_enabled = mnt_sign_required ? mnt_sign_required :
912                                 (global_secflags & CIFSSEC_MAY_SIGN);
913
914         /* If server requires signing, does client allow it? */
915         if (srv_sign_required) {
916                 if (!mnt_sign_enabled) {
917                         cifs_dbg(VFS, "Server requires signing, but it's disabled in SecurityFlags!\n");
918                         return -EOPNOTSUPP;
919                 }
920                 server->sign = true;
921         }
922
923         /* If client requires signing, does server allow it? */
924         if (mnt_sign_required) {
925                 if (!srv_sign_enabled) {
926                         cifs_dbg(VFS, "Server does not support signing!\n");
927                         return -EOPNOTSUPP;
928                 }
929                 server->sign = true;
930         }
931
932         if (cifs_rdma_enabled(server) && server->sign)
933                 cifs_dbg(VFS, "Signing is enabled, and RDMA read/write will be disabled\n");
934
935         return 0;
936 }
937
938 static noinline_for_stack void
939 clean_demultiplex_info(struct TCP_Server_Info *server)
940 {
941         int length;
942
943         /* take it off the list, if it's not already */
944         spin_lock(&server->srv_lock);
945         list_del_init(&server->tcp_ses_list);
946         spin_unlock(&server->srv_lock);
947
948         cancel_delayed_work_sync(&server->echo);
949
950         spin_lock(&server->srv_lock);
951         server->tcpStatus = CifsExiting;
952         spin_unlock(&server->srv_lock);
953         wake_up_all(&server->response_q);
954
955         /* check if we have blocked requests that need to free */
956         spin_lock(&server->req_lock);
957         if (server->credits <= 0)
958                 server->credits = 1;
959         spin_unlock(&server->req_lock);
960         /*
961          * Although there should not be any requests blocked on this queue it
962          * can not hurt to be paranoid and try to wake up requests that may
963          * haven been blocked when more than 50 at time were on the wire to the
964          * same server - they now will see the session is in exit state and get
965          * out of SendReceive.
966          */
967         wake_up_all(&server->request_q);
968         /* give those requests time to exit */
969         msleep(125);
970         if (cifs_rdma_enabled(server))
971                 smbd_destroy(server);
972         if (server->ssocket) {
973                 sock_release(server->ssocket);
974                 server->ssocket = NULL;
975         }
976
977         if (!list_empty(&server->pending_mid_q)) {
978                 struct list_head dispose_list;
979                 struct mid_q_entry *mid_entry;
980                 struct list_head *tmp, *tmp2;
981
982                 INIT_LIST_HEAD(&dispose_list);
983                 spin_lock(&server->mid_lock);
984                 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
985                         mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
986                         cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
987                         kref_get(&mid_entry->refcount);
988                         mid_entry->mid_state = MID_SHUTDOWN;
989                         list_move(&mid_entry->qhead, &dispose_list);
990                         mid_entry->mid_flags |= MID_DELETED;
991                 }
992                 spin_unlock(&server->mid_lock);
993
994                 /* now walk dispose list and issue callbacks */
995                 list_for_each_safe(tmp, tmp2, &dispose_list) {
996                         mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
997                         cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
998                         list_del_init(&mid_entry->qhead);
999                         mid_entry->callback(mid_entry);
1000                         release_mid(mid_entry);
1001                 }
1002                 /* 1/8th of sec is more than enough time for them to exit */
1003                 msleep(125);
1004         }
1005
1006         if (!list_empty(&server->pending_mid_q)) {
1007                 /*
1008                  * mpx threads have not exited yet give them at least the smb
1009                  * send timeout time for long ops.
1010                  *
1011                  * Due to delays on oplock break requests, we need to wait at
1012                  * least 45 seconds before giving up on a request getting a
1013                  * response and going ahead and killing cifsd.
1014                  */
1015                 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
1016                 msleep(46000);
1017                 /*
1018                  * If threads still have not exited they are probably never
1019                  * coming home not much else we can do but free the memory.
1020                  */
1021         }
1022
1023         kfree(server->leaf_fullpath);
1024         kfree(server);
1025
1026         length = atomic_dec_return(&tcpSesAllocCount);
1027         if (length > 0)
1028                 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1029 }
1030
1031 static int
1032 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1033 {
1034         int length;
1035         char *buf = server->smallbuf;
1036         unsigned int pdu_length = server->pdu_size;
1037
1038         /* make sure this will fit in a large buffer */
1039         if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
1040             HEADER_PREAMBLE_SIZE(server)) {
1041                 cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
1042                 cifs_reconnect(server, true);
1043                 return -ECONNABORTED;
1044         }
1045
1046         /* switch to large buffer if too big for a small one */
1047         if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
1048                 server->large_buf = true;
1049                 memcpy(server->bigbuf, buf, server->total_read);
1050                 buf = server->bigbuf;
1051         }
1052
1053         /* now read the rest */
1054         length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
1055                                        pdu_length - MID_HEADER_SIZE(server));
1056
1057         if (length < 0)
1058                 return length;
1059         server->total_read += length;
1060
1061         dump_smb(buf, server->total_read);
1062
1063         return cifs_handle_standard(server, mid);
1064 }
1065
1066 int
1067 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1068 {
1069         char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1070         int rc;
1071
1072         /*
1073          * We know that we received enough to get to the MID as we
1074          * checked the pdu_length earlier. Now check to see
1075          * if the rest of the header is OK.
1076          *
1077          * 48 bytes is enough to display the header and a little bit
1078          * into the payload for debugging purposes.
1079          */
1080         rc = server->ops->check_message(buf, server->total_read, server);
1081         if (rc)
1082                 cifs_dump_mem("Bad SMB: ", buf,
1083                         min_t(unsigned int, server->total_read, 48));
1084
1085         if (server->ops->is_session_expired &&
1086             server->ops->is_session_expired(buf)) {
1087                 cifs_reconnect(server, true);
1088                 return -1;
1089         }
1090
1091         if (server->ops->is_status_pending &&
1092             server->ops->is_status_pending(buf, server))
1093                 return -1;
1094
1095         if (!mid)
1096                 return rc;
1097
1098         handle_mid(mid, server, buf, rc);
1099         return 0;
1100 }
1101
1102 static void
1103 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1104 {
1105         struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1106         int scredits, in_flight;
1107
1108         /*
1109          * SMB1 does not use credits.
1110          */
1111         if (is_smb1(server))
1112                 return;
1113
1114         if (shdr->CreditRequest) {
1115                 spin_lock(&server->req_lock);
1116                 server->credits += le16_to_cpu(shdr->CreditRequest);
1117                 scredits = server->credits;
1118                 in_flight = server->in_flight;
1119                 spin_unlock(&server->req_lock);
1120                 wake_up(&server->request_q);
1121
1122                 trace_smb3_hdr_credits(server->CurrentMid,
1123                                 server->conn_id, server->hostname, scredits,
1124                                 le16_to_cpu(shdr->CreditRequest), in_flight);
1125                 cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
1126                                 __func__, le16_to_cpu(shdr->CreditRequest),
1127                                 scredits);
1128         }
1129 }
1130
1131
1132 static int
1133 cifs_demultiplex_thread(void *p)
1134 {
1135         int i, num_mids, length;
1136         struct TCP_Server_Info *server = p;
1137         unsigned int pdu_length;
1138         unsigned int next_offset;
1139         char *buf = NULL;
1140         struct task_struct *task_to_wake = NULL;
1141         struct mid_q_entry *mids[MAX_COMPOUND];
1142         char *bufs[MAX_COMPOUND];
1143         unsigned int noreclaim_flag, num_io_timeout = 0;
1144         bool pending_reconnect = false;
1145
1146         noreclaim_flag = memalloc_noreclaim_save();
1147         cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1148
1149         length = atomic_inc_return(&tcpSesAllocCount);
1150         if (length > 1)
1151                 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1152
1153         set_freezable();
1154         allow_kernel_signal(SIGKILL);
1155         while (server->tcpStatus != CifsExiting) {
1156                 if (try_to_freeze())
1157                         continue;
1158
1159                 if (!allocate_buffers(server))
1160                         continue;
1161
1162                 server->large_buf = false;
1163                 buf = server->smallbuf;
1164                 pdu_length = 4; /* enough to get RFC1001 header */
1165
1166                 length = cifs_read_from_socket(server, buf, pdu_length);
1167                 if (length < 0)
1168                         continue;
1169
1170                 if (is_smb1(server))
1171                         server->total_read = length;
1172                 else
1173                         server->total_read = 0;
1174
1175                 /*
1176                  * The right amount was read from socket - 4 bytes,
1177                  * so we can now interpret the length field.
1178                  */
1179                 pdu_length = get_rfc1002_length(buf);
1180
1181                 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1182                 if (!is_smb_response(server, buf[0]))
1183                         continue;
1184
1185                 pending_reconnect = false;
1186 next_pdu:
1187                 server->pdu_size = pdu_length;
1188
1189                 /* make sure we have enough to get to the MID */
1190                 if (server->pdu_size < MID_HEADER_SIZE(server)) {
1191                         cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1192                                  server->pdu_size);
1193                         cifs_reconnect(server, true);
1194                         continue;
1195                 }
1196
1197                 /* read down to the MID */
1198                 length = cifs_read_from_socket(server,
1199                              buf + HEADER_PREAMBLE_SIZE(server),
1200                              MID_HEADER_SIZE(server));
1201                 if (length < 0)
1202                         continue;
1203                 server->total_read += length;
1204
1205                 if (server->ops->next_header) {
1206                         if (server->ops->next_header(server, buf, &next_offset)) {
1207                                 cifs_dbg(VFS, "%s: malformed response (next_offset=%u)\n",
1208                                          __func__, next_offset);
1209                                 cifs_reconnect(server, true);
1210                                 continue;
1211                         }
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 > MAX_STATUS_IO_TIMEOUT) {
1249                                 cifs_server_dbg(VFS,
1250                                                 "Number of request timeouts exceeded %d. Reconnecting",
1251                                                 MAX_STATUS_IO_TIMEOUT);
1252
1253                                 pending_reconnect = true;
1254                                 num_io_timeout = 0;
1255                         }
1256                 }
1257
1258                 server->lstrp = jiffies;
1259
1260                 for (i = 0; i < num_mids; i++) {
1261                         if (mids[i] != NULL) {
1262                                 mids[i]->resp_buf_size = server->pdu_size;
1263
1264                                 if (bufs[i] != NULL) {
1265                                         if (server->ops->is_network_name_deleted &&
1266                                             server->ops->is_network_name_deleted(bufs[i],
1267                                                                                  server)) {
1268                                                 cifs_server_dbg(FYI,
1269                                                                 "Share deleted. Reconnect needed");
1270                                         }
1271                                 }
1272
1273                                 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1274                                         mids[i]->callback(mids[i]);
1275
1276                                 release_mid(mids[i]);
1277                         } else if (server->ops->is_oplock_break &&
1278                                    server->ops->is_oplock_break(bufs[i],
1279                                                                 server)) {
1280                                 smb2_add_credits_from_hdr(bufs[i], server);
1281                                 cifs_dbg(FYI, "Received oplock break\n");
1282                         } else {
1283                                 cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1284                                                 atomic_read(&mid_count));
1285                                 cifs_dump_mem("Received Data is: ", bufs[i],
1286                                               HEADER_SIZE(server));
1287                                 smb2_add_credits_from_hdr(bufs[i], server);
1288 #ifdef CONFIG_CIFS_DEBUG2
1289                                 if (server->ops->dump_detail)
1290                                         server->ops->dump_detail(bufs[i],
1291                                                                  server);
1292                                 cifs_dump_mids(server);
1293 #endif /* CIFS_DEBUG2 */
1294                         }
1295                 }
1296
1297                 if (pdu_length > server->pdu_size) {
1298                         if (!allocate_buffers(server))
1299                                 continue;
1300                         pdu_length -= server->pdu_size;
1301                         server->total_read = 0;
1302                         server->large_buf = false;
1303                         buf = server->smallbuf;
1304                         goto next_pdu;
1305                 }
1306
1307                 /* do this reconnect at the very end after processing all MIDs */
1308                 if (pending_reconnect)
1309                         cifs_reconnect(server, true);
1310
1311         } /* end while !EXITING */
1312
1313         /* buffer usually freed in free_mid - need to free it here on exit */
1314         cifs_buf_release(server->bigbuf);
1315         if (server->smallbuf) /* no sense logging a debug message if NULL */
1316                 cifs_small_buf_release(server->smallbuf);
1317
1318         task_to_wake = xchg(&server->tsk, NULL);
1319         clean_demultiplex_info(server);
1320
1321         /* if server->tsk was NULL then wait for a signal before exiting */
1322         if (!task_to_wake) {
1323                 set_current_state(TASK_INTERRUPTIBLE);
1324                 while (!signal_pending(current)) {
1325                         schedule();
1326                         set_current_state(TASK_INTERRUPTIBLE);
1327                 }
1328                 set_current_state(TASK_RUNNING);
1329         }
1330
1331         memalloc_noreclaim_restore(noreclaim_flag);
1332         module_put_and_kthread_exit(0);
1333 }
1334
1335 int
1336 cifs_ipaddr_cmp(struct sockaddr *srcaddr, struct sockaddr *rhs)
1337 {
1338         struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1339         struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1340         struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1341         struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1342
1343         switch (srcaddr->sa_family) {
1344         case AF_UNSPEC:
1345                 switch (rhs->sa_family) {
1346                 case AF_UNSPEC:
1347                         return 0;
1348                 case AF_INET:
1349                 case AF_INET6:
1350                         return 1;
1351                 default:
1352                         return -1;
1353                 }
1354         case AF_INET: {
1355                 switch (rhs->sa_family) {
1356                 case AF_UNSPEC:
1357                         return -1;
1358                 case AF_INET:
1359                         return memcmp(saddr4, vaddr4,
1360                                       sizeof(struct sockaddr_in));
1361                 case AF_INET6:
1362                         return 1;
1363                 default:
1364                         return -1;
1365                 }
1366         }
1367         case AF_INET6: {
1368                 switch (rhs->sa_family) {
1369                 case AF_UNSPEC:
1370                 case AF_INET:
1371                         return -1;
1372                 case AF_INET6:
1373                         return memcmp(saddr6,
1374                                       vaddr6,
1375                                       sizeof(struct sockaddr_in6));
1376                 default:
1377                         return -1;
1378                 }
1379         }
1380         default:
1381                 return -1; /* don't expect to be here */
1382         }
1383 }
1384
1385 /*
1386  * Returns true if srcaddr isn't specified and rhs isn't specified, or
1387  * if srcaddr is specified and matches the IP address of the rhs argument
1388  */
1389 bool
1390 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1391 {
1392         switch (srcaddr->sa_family) {
1393         case AF_UNSPEC:
1394                 return (rhs->sa_family == AF_UNSPEC);
1395         case AF_INET: {
1396                 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1397                 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1398
1399                 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1400         }
1401         case AF_INET6: {
1402                 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1403                 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1404
1405                 return (ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr)
1406                         && saddr6->sin6_scope_id == vaddr6->sin6_scope_id);
1407         }
1408         default:
1409                 WARN_ON(1);
1410                 return false; /* don't expect to be here */
1411         }
1412 }
1413
1414 /*
1415  * If no port is specified in addr structure, we try to match with 445 port
1416  * and if it fails - with 139 ports. It should be called only if address
1417  * families of server and addr are equal.
1418  */
1419 static bool
1420 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1421 {
1422         __be16 port, *sport;
1423
1424         /* SMBDirect manages its own ports, don't match it here */
1425         if (server->rdma)
1426                 return true;
1427
1428         switch (addr->sa_family) {
1429         case AF_INET:
1430                 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1431                 port = ((struct sockaddr_in *) addr)->sin_port;
1432                 break;
1433         case AF_INET6:
1434                 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1435                 port = ((struct sockaddr_in6 *) addr)->sin6_port;
1436                 break;
1437         default:
1438                 WARN_ON(1);
1439                 return false;
1440         }
1441
1442         if (!port) {
1443                 port = htons(CIFS_PORT);
1444                 if (port == *sport)
1445                         return true;
1446
1447                 port = htons(RFC1001_PORT);
1448         }
1449
1450         return port == *sport;
1451 }
1452
1453 static bool match_server_address(struct TCP_Server_Info *server, struct sockaddr *addr)
1454 {
1455         if (!cifs_match_ipaddr(addr, (struct sockaddr *)&server->dstaddr))
1456                 return false;
1457
1458         return true;
1459 }
1460
1461 static bool
1462 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1463 {
1464         /*
1465          * The select_sectype function should either return the ctx->sectype
1466          * that was specified, or "Unspecified" if that sectype was not
1467          * compatible with the given NEGOTIATE request.
1468          */
1469         if (server->ops->select_sectype(server, ctx->sectype)
1470              == Unspecified)
1471                 return false;
1472
1473         /*
1474          * Now check if signing mode is acceptable. No need to check
1475          * global_secflags at this point since if MUST_SIGN is set then
1476          * the server->sign had better be too.
1477          */
1478         if (ctx->sign && !server->sign)
1479                 return false;
1480
1481         return true;
1482 }
1483
1484 /* this function must be called with srv_lock held */
1485 static int match_server(struct TCP_Server_Info *server,
1486                         struct smb3_fs_context *ctx,
1487                         bool match_super)
1488 {
1489         struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1490
1491         lockdep_assert_held(&server->srv_lock);
1492
1493         if (ctx->nosharesock)
1494                 return 0;
1495
1496         /* this server does not share socket */
1497         if (server->nosharesock)
1498                 return 0;
1499
1500         /* If multidialect negotiation see if existing sessions match one */
1501         if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1502                 if (server->vals->protocol_id < SMB30_PROT_ID)
1503                         return 0;
1504         } else if (strcmp(ctx->vals->version_string,
1505                    SMBDEFAULT_VERSION_STRING) == 0) {
1506                 if (server->vals->protocol_id < SMB21_PROT_ID)
1507                         return 0;
1508         } else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1509                 return 0;
1510
1511         if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1512                 return 0;
1513
1514         if (!cifs_match_ipaddr((struct sockaddr *)&ctx->srcaddr,
1515                                (struct sockaddr *)&server->srcaddr))
1516                 return 0;
1517         /*
1518          * When matching cifs.ko superblocks (@match_super == true), we can't
1519          * really match either @server->leaf_fullpath or @server->dstaddr
1520          * directly since this @server might belong to a completely different
1521          * server -- in case of domain-based DFS referrals or DFS links -- as
1522          * provided earlier by mount(2) through 'source' and 'ip' options.
1523          *
1524          * Otherwise, match the DFS referral in @server->leaf_fullpath or the
1525          * destination address in @server->dstaddr.
1526          *
1527          * When using 'nodfs' mount option, we avoid sharing it with DFS
1528          * connections as they might failover.
1529          */
1530         if (!match_super) {
1531                 if (!ctx->nodfs) {
1532                         if (server->leaf_fullpath) {
1533                                 if (!ctx->leaf_fullpath ||
1534                                     strcasecmp(server->leaf_fullpath,
1535                                                ctx->leaf_fullpath))
1536                                         return 0;
1537                         } else if (ctx->leaf_fullpath) {
1538                                 return 0;
1539                         }
1540                 } else if (server->leaf_fullpath) {
1541                         return 0;
1542                 }
1543         }
1544
1545         /*
1546          * Match for a regular connection (address/hostname/port) which has no
1547          * DFS referrals set.
1548          */
1549         if (!server->leaf_fullpath &&
1550             (strcasecmp(server->hostname, ctx->server_hostname) ||
1551              !match_server_address(server, addr) ||
1552              !match_port(server, addr)))
1553                 return 0;
1554
1555         if (!match_security(server, ctx))
1556                 return 0;
1557
1558         if (server->echo_interval != ctx->echo_interval * HZ)
1559                 return 0;
1560
1561         if (server->rdma != ctx->rdma)
1562                 return 0;
1563
1564         if (server->ignore_signature != ctx->ignore_signature)
1565                 return 0;
1566
1567         if (server->min_offload != ctx->min_offload)
1568                 return 0;
1569
1570         return 1;
1571 }
1572
1573 struct TCP_Server_Info *
1574 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1575 {
1576         struct TCP_Server_Info *server;
1577
1578         spin_lock(&cifs_tcp_ses_lock);
1579         list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1580                 spin_lock(&server->srv_lock);
1581                 /*
1582                  * Skip ses channels since they're only handled in lower layers
1583                  * (e.g. cifs_send_recv).
1584                  */
1585                 if (SERVER_IS_CHAN(server) ||
1586                     !match_server(server, ctx, false)) {
1587                         spin_unlock(&server->srv_lock);
1588                         continue;
1589                 }
1590                 spin_unlock(&server->srv_lock);
1591
1592                 ++server->srv_count;
1593                 spin_unlock(&cifs_tcp_ses_lock);
1594                 cifs_dbg(FYI, "Existing tcp session with server found\n");
1595                 return server;
1596         }
1597         spin_unlock(&cifs_tcp_ses_lock);
1598         return NULL;
1599 }
1600
1601 void
1602 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1603 {
1604         struct task_struct *task;
1605
1606         spin_lock(&cifs_tcp_ses_lock);
1607         if (--server->srv_count > 0) {
1608                 spin_unlock(&cifs_tcp_ses_lock);
1609                 return;
1610         }
1611
1612         /* srv_count can never go negative */
1613         WARN_ON(server->srv_count < 0);
1614
1615         put_net(cifs_net_ns(server));
1616
1617         list_del_init(&server->tcp_ses_list);
1618         spin_unlock(&cifs_tcp_ses_lock);
1619
1620         cancel_delayed_work_sync(&server->echo);
1621
1622         if (from_reconnect)
1623                 /*
1624                  * Avoid deadlock here: reconnect work calls
1625                  * cifs_put_tcp_session() at its end. Need to be sure
1626                  * that reconnect work does nothing with server pointer after
1627                  * that step.
1628                  */
1629                 cancel_delayed_work(&server->reconnect);
1630         else
1631                 cancel_delayed_work_sync(&server->reconnect);
1632
1633         /* For secondary channels, we pick up ref-count on the primary server */
1634         if (SERVER_IS_CHAN(server))
1635                 cifs_put_tcp_session(server->primary_server, from_reconnect);
1636
1637         spin_lock(&server->srv_lock);
1638         server->tcpStatus = CifsExiting;
1639         spin_unlock(&server->srv_lock);
1640
1641         cifs_crypto_secmech_release(server);
1642
1643         kfree_sensitive(server->session_key.response);
1644         server->session_key.response = NULL;
1645         server->session_key.len = 0;
1646         kfree(server->hostname);
1647         server->hostname = NULL;
1648
1649         task = xchg(&server->tsk, NULL);
1650         if (task)
1651                 send_sig(SIGKILL, task, 1);
1652 }
1653
1654 struct TCP_Server_Info *
1655 cifs_get_tcp_session(struct smb3_fs_context *ctx,
1656                      struct TCP_Server_Info *primary_server)
1657 {
1658         struct TCP_Server_Info *tcp_ses = NULL;
1659         int rc;
1660
1661         cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1662
1663         /* see if we already have a matching tcp_ses */
1664         tcp_ses = cifs_find_tcp_session(ctx);
1665         if (tcp_ses)
1666                 return tcp_ses;
1667
1668         tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1669         if (!tcp_ses) {
1670                 rc = -ENOMEM;
1671                 goto out_err;
1672         }
1673
1674         tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1675         if (!tcp_ses->hostname) {
1676                 rc = -ENOMEM;
1677                 goto out_err;
1678         }
1679
1680         if (ctx->leaf_fullpath) {
1681                 tcp_ses->leaf_fullpath = kstrdup(ctx->leaf_fullpath, GFP_KERNEL);
1682                 if (!tcp_ses->leaf_fullpath) {
1683                         rc = -ENOMEM;
1684                         goto out_err;
1685                 }
1686         }
1687
1688         if (ctx->nosharesock)
1689                 tcp_ses->nosharesock = true;
1690
1691         tcp_ses->ops = ctx->ops;
1692         tcp_ses->vals = ctx->vals;
1693         cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1694
1695         tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1696         tcp_ses->noblockcnt = ctx->rootfs;
1697         tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1698         tcp_ses->noautotune = ctx->noautotune;
1699         tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1700         tcp_ses->rdma = ctx->rdma;
1701         tcp_ses->in_flight = 0;
1702         tcp_ses->max_in_flight = 0;
1703         tcp_ses->credits = 1;
1704         if (primary_server) {
1705                 spin_lock(&cifs_tcp_ses_lock);
1706                 ++primary_server->srv_count;
1707                 spin_unlock(&cifs_tcp_ses_lock);
1708                 tcp_ses->primary_server = primary_server;
1709         }
1710         init_waitqueue_head(&tcp_ses->response_q);
1711         init_waitqueue_head(&tcp_ses->request_q);
1712         INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1713         mutex_init(&tcp_ses->_srv_mutex);
1714         memcpy(tcp_ses->workstation_RFC1001_name,
1715                 ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1716         memcpy(tcp_ses->server_RFC1001_name,
1717                 ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1718         tcp_ses->session_estab = false;
1719         tcp_ses->sequence_number = 0;
1720         tcp_ses->channel_sequence_num = 0; /* only tracked for primary channel */
1721         tcp_ses->reconnect_instance = 1;
1722         tcp_ses->lstrp = jiffies;
1723         tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1724         spin_lock_init(&tcp_ses->req_lock);
1725         spin_lock_init(&tcp_ses->srv_lock);
1726         spin_lock_init(&tcp_ses->mid_lock);
1727         INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1728         INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1729         INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1730         INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1731         mutex_init(&tcp_ses->reconnect_mutex);
1732 #ifdef CONFIG_CIFS_DFS_UPCALL
1733         mutex_init(&tcp_ses->refpath_lock);
1734 #endif
1735         memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1736                sizeof(tcp_ses->srcaddr));
1737         memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1738                 sizeof(tcp_ses->dstaddr));
1739         if (ctx->use_client_guid)
1740                 memcpy(tcp_ses->client_guid, ctx->client_guid,
1741                        SMB2_CLIENT_GUID_SIZE);
1742         else
1743                 generate_random_uuid(tcp_ses->client_guid);
1744         /*
1745          * at this point we are the only ones with the pointer
1746          * to the struct since the kernel thread not created yet
1747          * no need to spinlock this init of tcpStatus or srv_count
1748          */
1749         tcp_ses->tcpStatus = CifsNew;
1750         ++tcp_ses->srv_count;
1751
1752         if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1753                 ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1754                 tcp_ses->echo_interval = ctx->echo_interval * HZ;
1755         else
1756                 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1757         if (tcp_ses->rdma) {
1758 #ifndef CONFIG_CIFS_SMB_DIRECT
1759                 cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1760                 rc = -ENOENT;
1761                 goto out_err_crypto_release;
1762 #endif
1763                 tcp_ses->smbd_conn = smbd_get_connection(
1764                         tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1765                 if (tcp_ses->smbd_conn) {
1766                         cifs_dbg(VFS, "RDMA transport established\n");
1767                         rc = 0;
1768                         goto smbd_connected;
1769                 } else {
1770                         rc = -ENOENT;
1771                         goto out_err_crypto_release;
1772                 }
1773         }
1774         rc = ip_connect(tcp_ses);
1775         if (rc < 0) {
1776                 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1777                 goto out_err_crypto_release;
1778         }
1779 smbd_connected:
1780         /*
1781          * since we're in a cifs function already, we know that
1782          * this will succeed. No need for try_module_get().
1783          */
1784         __module_get(THIS_MODULE);
1785         tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1786                                   tcp_ses, "cifsd");
1787         if (IS_ERR(tcp_ses->tsk)) {
1788                 rc = PTR_ERR(tcp_ses->tsk);
1789                 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1790                 module_put(THIS_MODULE);
1791                 goto out_err_crypto_release;
1792         }
1793         tcp_ses->min_offload = ctx->min_offload;
1794         /*
1795          * at this point we are the only ones with the pointer
1796          * to the struct since the kernel thread not created yet
1797          * no need to spinlock this update of tcpStatus
1798          */
1799         spin_lock(&tcp_ses->srv_lock);
1800         tcp_ses->tcpStatus = CifsNeedNegotiate;
1801         spin_unlock(&tcp_ses->srv_lock);
1802
1803         if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1804                 tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1805         else
1806                 tcp_ses->max_credits = ctx->max_credits;
1807
1808         tcp_ses->nr_targets = 1;
1809         tcp_ses->ignore_signature = ctx->ignore_signature;
1810         /* thread spawned, put it on the list */
1811         spin_lock(&cifs_tcp_ses_lock);
1812         list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1813         spin_unlock(&cifs_tcp_ses_lock);
1814
1815         /* queue echo request delayed work */
1816         queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1817
1818         return tcp_ses;
1819
1820 out_err_crypto_release:
1821         cifs_crypto_secmech_release(tcp_ses);
1822
1823         put_net(cifs_net_ns(tcp_ses));
1824
1825 out_err:
1826         if (tcp_ses) {
1827                 if (SERVER_IS_CHAN(tcp_ses))
1828                         cifs_put_tcp_session(tcp_ses->primary_server, false);
1829                 kfree(tcp_ses->hostname);
1830                 kfree(tcp_ses->leaf_fullpath);
1831                 if (tcp_ses->ssocket)
1832                         sock_release(tcp_ses->ssocket);
1833                 kfree(tcp_ses);
1834         }
1835         return ERR_PTR(rc);
1836 }
1837
1838 /* this function must be called with ses_lock and chan_lock held */
1839 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1840 {
1841         if (ctx->sectype != Unspecified &&
1842             ctx->sectype != ses->sectype)
1843                 return 0;
1844
1845         /*
1846          * If an existing session is limited to less channels than
1847          * requested, it should not be reused
1848          */
1849         if (ses->chan_max < ctx->max_channels)
1850                 return 0;
1851
1852         switch (ses->sectype) {
1853         case Kerberos:
1854                 if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1855                         return 0;
1856                 break;
1857         default:
1858                 /* NULL username means anonymous session */
1859                 if (ses->user_name == NULL) {
1860                         if (!ctx->nullauth)
1861                                 return 0;
1862                         break;
1863                 }
1864
1865                 /* anything else takes username/password */
1866                 if (strncmp(ses->user_name,
1867                             ctx->username ? ctx->username : "",
1868                             CIFS_MAX_USERNAME_LEN))
1869                         return 0;
1870                 if ((ctx->username && strlen(ctx->username) != 0) &&
1871                     ses->password != NULL &&
1872                     strncmp(ses->password,
1873                             ctx->password ? ctx->password : "",
1874                             CIFS_MAX_PASSWORD_LEN))
1875                         return 0;
1876         }
1877
1878         if (strcmp(ctx->local_nls->charset, ses->local_nls->charset))
1879                 return 0;
1880
1881         return 1;
1882 }
1883
1884 /**
1885  * cifs_setup_ipc - helper to setup the IPC tcon for the session
1886  * @ses: smb session to issue the request on
1887  * @ctx: the superblock configuration context to use for building the
1888  *       new tree connection for the IPC (interprocess communication RPC)
1889  *
1890  * A new IPC connection is made and stored in the session
1891  * tcon_ipc. The IPC tcon has the same lifetime as the session.
1892  */
1893 static int
1894 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1895 {
1896         int rc = 0, xid;
1897         struct cifs_tcon *tcon;
1898         char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1899         bool seal = false;
1900         struct TCP_Server_Info *server = ses->server;
1901
1902         /*
1903          * If the mount request that resulted in the creation of the
1904          * session requires encryption, force IPC to be encrypted too.
1905          */
1906         if (ctx->seal) {
1907                 if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1908                         seal = true;
1909                 else {
1910                         cifs_server_dbg(VFS,
1911                                  "IPC: server doesn't support encryption\n");
1912                         return -EOPNOTSUPP;
1913                 }
1914         }
1915
1916         /* no need to setup directory caching on IPC share, so pass in false */
1917         tcon = tcon_info_alloc(false);
1918         if (tcon == NULL)
1919                 return -ENOMEM;
1920
1921         spin_lock(&server->srv_lock);
1922         scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1923         spin_unlock(&server->srv_lock);
1924
1925         xid = get_xid();
1926         tcon->ses = ses;
1927         tcon->ipc = true;
1928         tcon->seal = seal;
1929         rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1930         free_xid(xid);
1931
1932         if (rc) {
1933                 cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1934                 tconInfoFree(tcon);
1935                 goto out;
1936         }
1937
1938         cifs_dbg(FYI, "IPC tcon rc=%d ipc tid=0x%x\n", rc, tcon->tid);
1939
1940         spin_lock(&tcon->tc_lock);
1941         tcon->status = TID_GOOD;
1942         spin_unlock(&tcon->tc_lock);
1943         ses->tcon_ipc = tcon;
1944 out:
1945         return rc;
1946 }
1947
1948 /**
1949  * cifs_free_ipc - helper to release the session IPC tcon
1950  * @ses: smb session to unmount the IPC from
1951  *
1952  * Needs to be called everytime a session is destroyed.
1953  *
1954  * On session close, the IPC is closed and the server must release all tcons of the session.
1955  * No need to send a tree disconnect here.
1956  *
1957  * Besides, it will make the server to not close durable and resilient files on session close, as
1958  * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1959  */
1960 static int
1961 cifs_free_ipc(struct cifs_ses *ses)
1962 {
1963         struct cifs_tcon *tcon = ses->tcon_ipc;
1964
1965         if (tcon == NULL)
1966                 return 0;
1967
1968         tconInfoFree(tcon);
1969         ses->tcon_ipc = NULL;
1970         return 0;
1971 }
1972
1973 static struct cifs_ses *
1974 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1975 {
1976         struct cifs_ses *ses, *ret = NULL;
1977
1978         spin_lock(&cifs_tcp_ses_lock);
1979         list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1980                 spin_lock(&ses->ses_lock);
1981                 if (ses->ses_status == SES_EXITING) {
1982                         spin_unlock(&ses->ses_lock);
1983                         continue;
1984                 }
1985                 spin_lock(&ses->chan_lock);
1986                 if (match_session(ses, ctx)) {
1987                         spin_unlock(&ses->chan_lock);
1988                         spin_unlock(&ses->ses_lock);
1989                         ret = ses;
1990                         break;
1991                 }
1992                 spin_unlock(&ses->chan_lock);
1993                 spin_unlock(&ses->ses_lock);
1994         }
1995         if (ret)
1996                 cifs_smb_ses_inc_refcount(ret);
1997         spin_unlock(&cifs_tcp_ses_lock);
1998         return ret;
1999 }
2000
2001 void __cifs_put_smb_ses(struct cifs_ses *ses)
2002 {
2003         struct TCP_Server_Info *server = ses->server;
2004         unsigned int xid;
2005         size_t i;
2006         int rc;
2007
2008         spin_lock(&ses->ses_lock);
2009         if (ses->ses_status == SES_EXITING) {
2010                 spin_unlock(&ses->ses_lock);
2011                 return;
2012         }
2013         spin_unlock(&ses->ses_lock);
2014
2015         cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
2016         cifs_dbg(FYI,
2017                  "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->tree_name : "NONE");
2018
2019         spin_lock(&cifs_tcp_ses_lock);
2020         if (--ses->ses_count > 0) {
2021                 spin_unlock(&cifs_tcp_ses_lock);
2022                 return;
2023         }
2024         spin_lock(&ses->ses_lock);
2025         if (ses->ses_status == SES_GOOD)
2026                 ses->ses_status = SES_EXITING;
2027         spin_unlock(&ses->ses_lock);
2028         spin_unlock(&cifs_tcp_ses_lock);
2029
2030         /* ses_count can never go negative */
2031         WARN_ON(ses->ses_count < 0);
2032
2033         spin_lock(&ses->ses_lock);
2034         if (ses->ses_status == SES_EXITING && server->ops->logoff) {
2035                 spin_unlock(&ses->ses_lock);
2036                 cifs_free_ipc(ses);
2037                 xid = get_xid();
2038                 rc = server->ops->logoff(xid, ses);
2039                 if (rc)
2040                         cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
2041                                 __func__, rc);
2042                 _free_xid(xid);
2043         } else {
2044                 spin_unlock(&ses->ses_lock);
2045                 cifs_free_ipc(ses);
2046         }
2047
2048         spin_lock(&cifs_tcp_ses_lock);
2049         list_del_init(&ses->smb_ses_list);
2050         spin_unlock(&cifs_tcp_ses_lock);
2051
2052         /* close any extra channels */
2053         for (i = 1; i < ses->chan_count; i++) {
2054                 if (ses->chans[i].iface) {
2055                         kref_put(&ses->chans[i].iface->refcount, release_iface);
2056                         ses->chans[i].iface = NULL;
2057                 }
2058                 cifs_put_tcp_session(ses->chans[i].server, 0);
2059                 ses->chans[i].server = NULL;
2060         }
2061
2062         /* we now account for primary channel in iface->refcount */
2063         if (ses->chans[0].iface) {
2064                 kref_put(&ses->chans[0].iface->refcount, release_iface);
2065                 ses->chans[0].server = NULL;
2066         }
2067
2068         sesInfoFree(ses);
2069         cifs_put_tcp_session(server, 0);
2070 }
2071
2072 #ifdef CONFIG_KEYS
2073
2074 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2075 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2076
2077 /* Populate username and pw fields from keyring if possible */
2078 static int
2079 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
2080 {
2081         int rc = 0;
2082         int is_domain = 0;
2083         const char *delim, *payload;
2084         char *desc;
2085         ssize_t len;
2086         struct key *key;
2087         struct TCP_Server_Info *server = ses->server;
2088         struct sockaddr_in *sa;
2089         struct sockaddr_in6 *sa6;
2090         const struct user_key_payload *upayload;
2091
2092         desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2093         if (!desc)
2094                 return -ENOMEM;
2095
2096         /* try to find an address key first */
2097         switch (server->dstaddr.ss_family) {
2098         case AF_INET:
2099                 sa = (struct sockaddr_in *)&server->dstaddr;
2100                 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2101                 break;
2102         case AF_INET6:
2103                 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2104                 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2105                 break;
2106         default:
2107                 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2108                          server->dstaddr.ss_family);
2109                 rc = -EINVAL;
2110                 goto out_err;
2111         }
2112
2113         cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2114         key = request_key(&key_type_logon, desc, "");
2115         if (IS_ERR(key)) {
2116                 if (!ses->domainName) {
2117                         cifs_dbg(FYI, "domainName is NULL\n");
2118                         rc = PTR_ERR(key);
2119                         goto out_err;
2120                 }
2121
2122                 /* didn't work, try to find a domain key */
2123                 sprintf(desc, "cifs:d:%s", ses->domainName);
2124                 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2125                 key = request_key(&key_type_logon, desc, "");
2126                 if (IS_ERR(key)) {
2127                         rc = PTR_ERR(key);
2128                         goto out_err;
2129                 }
2130                 is_domain = 1;
2131         }
2132
2133         down_read(&key->sem);
2134         upayload = user_key_payload_locked(key);
2135         if (IS_ERR_OR_NULL(upayload)) {
2136                 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2137                 goto out_key_put;
2138         }
2139
2140         /* find first : in payload */
2141         payload = upayload->data;
2142         delim = strnchr(payload, upayload->datalen, ':');
2143         cifs_dbg(FYI, "payload=%s\n", payload);
2144         if (!delim) {
2145                 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2146                          upayload->datalen);
2147                 rc = -EINVAL;
2148                 goto out_key_put;
2149         }
2150
2151         len = delim - payload;
2152         if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2153                 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2154                          len);
2155                 rc = -EINVAL;
2156                 goto out_key_put;
2157         }
2158
2159         ctx->username = kstrndup(payload, len, GFP_KERNEL);
2160         if (!ctx->username) {
2161                 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2162                          len);
2163                 rc = -ENOMEM;
2164                 goto out_key_put;
2165         }
2166         cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
2167
2168         len = key->datalen - (len + 1);
2169         if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2170                 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2171                 rc = -EINVAL;
2172                 kfree(ctx->username);
2173                 ctx->username = NULL;
2174                 goto out_key_put;
2175         }
2176
2177         ++delim;
2178         ctx->password = kstrndup(delim, len, GFP_KERNEL);
2179         if (!ctx->password) {
2180                 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2181                          len);
2182                 rc = -ENOMEM;
2183                 kfree(ctx->username);
2184                 ctx->username = NULL;
2185                 goto out_key_put;
2186         }
2187
2188         /*
2189          * If we have a domain key then we must set the domainName in the
2190          * for the request.
2191          */
2192         if (is_domain && ses->domainName) {
2193                 ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2194                 if (!ctx->domainname) {
2195                         cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
2196                                  len);
2197                         rc = -ENOMEM;
2198                         kfree(ctx->username);
2199                         ctx->username = NULL;
2200                         kfree_sensitive(ctx->password);
2201                         ctx->password = NULL;
2202                         goto out_key_put;
2203                 }
2204         }
2205
2206         strscpy(ctx->workstation_name, ses->workstation_name, sizeof(ctx->workstation_name));
2207
2208 out_key_put:
2209         up_read(&key->sem);
2210         key_put(key);
2211 out_err:
2212         kfree(desc);
2213         cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2214         return rc;
2215 }
2216 #else /* ! CONFIG_KEYS */
2217 static inline int
2218 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2219                    struct cifs_ses *ses __attribute__((unused)))
2220 {
2221         return -ENOSYS;
2222 }
2223 #endif /* CONFIG_KEYS */
2224
2225 /**
2226  * cifs_get_smb_ses - get a session matching @ctx data from @server
2227  * @server: server to setup the session to
2228  * @ctx: superblock configuration context to use to setup the session
2229  *
2230  * This function assumes it is being called from cifs_mount() where we
2231  * already got a server reference (server refcount +1). See
2232  * cifs_get_tcon() for refcount explanations.
2233  */
2234 struct cifs_ses *
2235 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2236 {
2237         int rc = 0;
2238         unsigned int xid;
2239         struct cifs_ses *ses;
2240         struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2241         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2242
2243         xid = get_xid();
2244
2245         ses = cifs_find_smb_ses(server, ctx);
2246         if (ses) {
2247                 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2248                          ses->ses_status);
2249
2250                 spin_lock(&ses->chan_lock);
2251                 if (cifs_chan_needs_reconnect(ses, server)) {
2252                         spin_unlock(&ses->chan_lock);
2253                         cifs_dbg(FYI, "Session needs reconnect\n");
2254
2255                         mutex_lock(&ses->session_mutex);
2256                         rc = cifs_negotiate_protocol(xid, ses, server);
2257                         if (rc) {
2258                                 mutex_unlock(&ses->session_mutex);
2259                                 /* problem -- put our ses reference */
2260                                 cifs_put_smb_ses(ses);
2261                                 free_xid(xid);
2262                                 return ERR_PTR(rc);
2263                         }
2264
2265                         rc = cifs_setup_session(xid, ses, server,
2266                                                 ctx->local_nls);
2267                         if (rc) {
2268                                 mutex_unlock(&ses->session_mutex);
2269                                 /* problem -- put our reference */
2270                                 cifs_put_smb_ses(ses);
2271                                 free_xid(xid);
2272                                 return ERR_PTR(rc);
2273                         }
2274                         mutex_unlock(&ses->session_mutex);
2275
2276                         spin_lock(&ses->chan_lock);
2277                 }
2278                 spin_unlock(&ses->chan_lock);
2279
2280                 /* existing SMB ses has a server reference already */
2281                 cifs_put_tcp_session(server, 0);
2282                 free_xid(xid);
2283                 return ses;
2284         }
2285
2286         rc = -ENOMEM;
2287
2288         cifs_dbg(FYI, "Existing smb sess not found\n");
2289         ses = sesInfoAlloc();
2290         if (ses == NULL)
2291                 goto get_ses_fail;
2292
2293         /* new SMB session uses our server ref */
2294         ses->server = server;
2295         if (server->dstaddr.ss_family == AF_INET6)
2296                 sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2297         else
2298                 sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2299
2300         if (ctx->username) {
2301                 ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2302                 if (!ses->user_name)
2303                         goto get_ses_fail;
2304         }
2305
2306         /* ctx->password freed at unmount */
2307         if (ctx->password) {
2308                 ses->password = kstrdup(ctx->password, GFP_KERNEL);
2309                 if (!ses->password)
2310                         goto get_ses_fail;
2311         }
2312         if (ctx->domainname) {
2313                 ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2314                 if (!ses->domainName)
2315                         goto get_ses_fail;
2316         }
2317
2318         strscpy(ses->workstation_name, ctx->workstation_name, sizeof(ses->workstation_name));
2319
2320         if (ctx->domainauto)
2321                 ses->domainAuto = ctx->domainauto;
2322         ses->cred_uid = ctx->cred_uid;
2323         ses->linux_uid = ctx->linux_uid;
2324
2325         ses->sectype = ctx->sectype;
2326         ses->sign = ctx->sign;
2327         ses->local_nls = load_nls(ctx->local_nls->charset);
2328
2329         /* add server as first channel */
2330         spin_lock(&ses->chan_lock);
2331         ses->chans[0].server = server;
2332         ses->chan_count = 1;
2333         ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2334         ses->chans_need_reconnect = 1;
2335         spin_unlock(&ses->chan_lock);
2336
2337         mutex_lock(&ses->session_mutex);
2338         rc = cifs_negotiate_protocol(xid, ses, server);
2339         if (!rc)
2340                 rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2341         mutex_unlock(&ses->session_mutex);
2342
2343         /* each channel uses a different signing key */
2344         spin_lock(&ses->chan_lock);
2345         memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2346                sizeof(ses->smb3signingkey));
2347         spin_unlock(&ses->chan_lock);
2348
2349         if (rc)
2350                 goto get_ses_fail;
2351
2352         /*
2353          * success, put it on the list and add it as first channel
2354          * note: the session becomes active soon after this. So you'll
2355          * need to lock before changing something in the session.
2356          */
2357         spin_lock(&cifs_tcp_ses_lock);
2358         ses->dfs_root_ses = ctx->dfs_root_ses;
2359         if (ses->dfs_root_ses)
2360                 ses->dfs_root_ses->ses_count++;
2361         list_add(&ses->smb_ses_list, &server->smb_ses_list);
2362         spin_unlock(&cifs_tcp_ses_lock);
2363
2364         cifs_setup_ipc(ses, ctx);
2365
2366         free_xid(xid);
2367
2368         return ses;
2369
2370 get_ses_fail:
2371         sesInfoFree(ses);
2372         free_xid(xid);
2373         return ERR_PTR(rc);
2374 }
2375
2376 /* this function must be called with tc_lock held */
2377 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2378 {
2379         struct TCP_Server_Info *server = tcon->ses->server;
2380
2381         if (tcon->status == TID_EXITING)
2382                 return 0;
2383
2384         if (tcon->origin_fullpath) {
2385                 if (!ctx->source ||
2386                     !dfs_src_pathname_equal(ctx->source,
2387                                             tcon->origin_fullpath))
2388                         return 0;
2389         } else if (!server->leaf_fullpath &&
2390                    strncmp(tcon->tree_name, ctx->UNC, MAX_TREE_SIZE)) {
2391                 return 0;
2392         }
2393         if (tcon->seal != ctx->seal)
2394                 return 0;
2395         if (tcon->snapshot_time != ctx->snapshot_time)
2396                 return 0;
2397         if (tcon->handle_timeout != ctx->handle_timeout)
2398                 return 0;
2399         if (tcon->no_lease != ctx->no_lease)
2400                 return 0;
2401         if (tcon->nodelete != ctx->nodelete)
2402                 return 0;
2403         return 1;
2404 }
2405
2406 static struct cifs_tcon *
2407 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2408 {
2409         struct cifs_tcon *tcon;
2410
2411         spin_lock(&cifs_tcp_ses_lock);
2412         list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2413                 spin_lock(&tcon->tc_lock);
2414                 if (!match_tcon(tcon, ctx)) {
2415                         spin_unlock(&tcon->tc_lock);
2416                         continue;
2417                 }
2418                 ++tcon->tc_count;
2419                 spin_unlock(&tcon->tc_lock);
2420                 spin_unlock(&cifs_tcp_ses_lock);
2421                 return tcon;
2422         }
2423         spin_unlock(&cifs_tcp_ses_lock);
2424         return NULL;
2425 }
2426
2427 void
2428 cifs_put_tcon(struct cifs_tcon *tcon)
2429 {
2430         unsigned int xid;
2431         struct cifs_ses *ses;
2432
2433         /*
2434          * IPC tcon share the lifetime of their session and are
2435          * destroyed in the session put function
2436          */
2437         if (tcon == NULL || tcon->ipc)
2438                 return;
2439
2440         ses = tcon->ses;
2441         cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2442         spin_lock(&cifs_tcp_ses_lock);
2443         spin_lock(&tcon->tc_lock);
2444         if (--tcon->tc_count > 0) {
2445                 spin_unlock(&tcon->tc_lock);
2446                 spin_unlock(&cifs_tcp_ses_lock);
2447                 return;
2448         }
2449
2450         /* tc_count can never go negative */
2451         WARN_ON(tcon->tc_count < 0);
2452
2453         list_del_init(&tcon->tcon_list);
2454         tcon->status = TID_EXITING;
2455         spin_unlock(&tcon->tc_lock);
2456         spin_unlock(&cifs_tcp_ses_lock);
2457
2458         /* cancel polling of interfaces */
2459         cancel_delayed_work_sync(&tcon->query_interfaces);
2460 #ifdef CONFIG_CIFS_DFS_UPCALL
2461         cancel_delayed_work_sync(&tcon->dfs_cache_work);
2462 #endif
2463
2464         if (tcon->use_witness) {
2465                 int rc;
2466
2467                 rc = cifs_swn_unregister(tcon);
2468                 if (rc < 0) {
2469                         cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2470                                         __func__, rc);
2471                 }
2472         }
2473
2474         xid = get_xid();
2475         if (ses->server->ops->tree_disconnect)
2476                 ses->server->ops->tree_disconnect(xid, tcon);
2477         _free_xid(xid);
2478
2479         cifs_fscache_release_super_cookie(tcon);
2480         tconInfoFree(tcon);
2481         cifs_put_smb_ses(ses);
2482 }
2483
2484 /**
2485  * cifs_get_tcon - get a tcon matching @ctx data from @ses
2486  * @ses: smb session to issue the request on
2487  * @ctx: the superblock configuration context to use for building the
2488  *
2489  * - tcon refcount is the number of mount points using the tcon.
2490  * - ses refcount is the number of tcon using the session.
2491  *
2492  * 1. This function assumes it is being called from cifs_mount() where
2493  *    we already got a session reference (ses refcount +1).
2494  *
2495  * 2. Since we're in the context of adding a mount point, the end
2496  *    result should be either:
2497  *
2498  * a) a new tcon already allocated with refcount=1 (1 mount point) and
2499  *    its session refcount incremented (1 new tcon). This +1 was
2500  *    already done in (1).
2501  *
2502  * b) an existing tcon with refcount+1 (add a mount point to it) and
2503  *    identical ses refcount (no new tcon). Because of (1) we need to
2504  *    decrement the ses refcount.
2505  */
2506 static struct cifs_tcon *
2507 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2508 {
2509         struct cifs_tcon *tcon;
2510         bool nohandlecache;
2511         int rc, xid;
2512
2513         tcon = cifs_find_tcon(ses, ctx);
2514         if (tcon) {
2515                 /*
2516                  * tcon has refcount already incremented but we need to
2517                  * decrement extra ses reference gotten by caller (case b)
2518                  */
2519                 cifs_dbg(FYI, "Found match on UNC path\n");
2520                 cifs_put_smb_ses(ses);
2521                 return tcon;
2522         }
2523
2524         if (!ses->server->ops->tree_connect) {
2525                 rc = -ENOSYS;
2526                 goto out_fail;
2527         }
2528
2529         if (ses->server->dialect >= SMB20_PROT_ID &&
2530             (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING))
2531                 nohandlecache = ctx->nohandlecache;
2532         else
2533                 nohandlecache = true;
2534         tcon = tcon_info_alloc(!nohandlecache);
2535         if (tcon == NULL) {
2536                 rc = -ENOMEM;
2537                 goto out_fail;
2538         }
2539         tcon->nohandlecache = nohandlecache;
2540
2541         if (ctx->snapshot_time) {
2542                 if (ses->server->vals->protocol_id == 0) {
2543                         cifs_dbg(VFS,
2544                              "Use SMB2 or later for snapshot mount option\n");
2545                         rc = -EOPNOTSUPP;
2546                         goto out_fail;
2547                 } else
2548                         tcon->snapshot_time = ctx->snapshot_time;
2549         }
2550
2551         if (ctx->handle_timeout) {
2552                 if (ses->server->vals->protocol_id == 0) {
2553                         cifs_dbg(VFS,
2554                              "Use SMB2.1 or later for handle timeout option\n");
2555                         rc = -EOPNOTSUPP;
2556                         goto out_fail;
2557                 } else
2558                         tcon->handle_timeout = ctx->handle_timeout;
2559         }
2560
2561         tcon->ses = ses;
2562         if (ctx->password) {
2563                 tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2564                 if (!tcon->password) {
2565                         rc = -ENOMEM;
2566                         goto out_fail;
2567                 }
2568         }
2569
2570         if (ctx->seal) {
2571                 if (ses->server->vals->protocol_id == 0) {
2572                         cifs_dbg(VFS,
2573                                  "SMB3 or later required for encryption\n");
2574                         rc = -EOPNOTSUPP;
2575                         goto out_fail;
2576                 } else if (tcon->ses->server->capabilities &
2577                                         SMB2_GLOBAL_CAP_ENCRYPTION)
2578                         tcon->seal = true;
2579                 else {
2580                         cifs_dbg(VFS, "Encryption is not supported on share\n");
2581                         rc = -EOPNOTSUPP;
2582                         goto out_fail;
2583                 }
2584         }
2585
2586         if (ctx->linux_ext) {
2587                 if (ses->server->posix_ext_supported) {
2588                         tcon->posix_extensions = true;
2589                         pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2590                 } else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
2591                     (strcmp(ses->server->vals->version_string,
2592                      SMB3ANY_VERSION_STRING) == 0) ||
2593                     (strcmp(ses->server->vals->version_string,
2594                      SMBDEFAULT_VERSION_STRING) == 0)) {
2595                         cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2596                         rc = -EOPNOTSUPP;
2597                         goto out_fail;
2598                 } else {
2599                         cifs_dbg(VFS,
2600                                 "Check vers= mount option. SMB3.11 disabled but required for POSIX extensions\n");
2601                         rc = -EOPNOTSUPP;
2602                         goto out_fail;
2603                 }
2604         }
2605
2606         xid = get_xid();
2607         rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2608                                             ctx->local_nls);
2609         free_xid(xid);
2610         cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2611         if (rc)
2612                 goto out_fail;
2613
2614         tcon->use_persistent = false;
2615         /* check if SMB2 or later, CIFS does not support persistent handles */
2616         if (ctx->persistent) {
2617                 if (ses->server->vals->protocol_id == 0) {
2618                         cifs_dbg(VFS,
2619                              "SMB3 or later required for persistent handles\n");
2620                         rc = -EOPNOTSUPP;
2621                         goto out_fail;
2622                 } else if (ses->server->capabilities &
2623                            SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2624                         tcon->use_persistent = true;
2625                 else /* persistent handles requested but not supported */ {
2626                         cifs_dbg(VFS,
2627                                 "Persistent handles not supported on share\n");
2628                         rc = -EOPNOTSUPP;
2629                         goto out_fail;
2630                 }
2631         } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2632              && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2633              && (ctx->nopersistent == false)) {
2634                 cifs_dbg(FYI, "enabling persistent handles\n");
2635                 tcon->use_persistent = true;
2636         } else if (ctx->resilient) {
2637                 if (ses->server->vals->protocol_id == 0) {
2638                         cifs_dbg(VFS,
2639                              "SMB2.1 or later required for resilient handles\n");
2640                         rc = -EOPNOTSUPP;
2641                         goto out_fail;
2642                 }
2643                 tcon->use_resilient = true;
2644         }
2645
2646         tcon->use_witness = false;
2647         if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2648                 if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2649                         if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2650                                 /*
2651                                  * Set witness in use flag in first place
2652                                  * to retry registration in the echo task
2653                                  */
2654                                 tcon->use_witness = true;
2655                                 /* And try to register immediately */
2656                                 rc = cifs_swn_register(tcon);
2657                                 if (rc < 0) {
2658                                         cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2659                                         goto out_fail;
2660                                 }
2661                         } else {
2662                                 /* TODO: try to extend for non-cluster uses (eg multichannel) */
2663                                 cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2664                                 rc = -EOPNOTSUPP;
2665                                 goto out_fail;
2666                         }
2667                 } else {
2668                         cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2669                         rc = -EOPNOTSUPP;
2670                         goto out_fail;
2671                 }
2672         }
2673
2674         /* If the user really knows what they are doing they can override */
2675         if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2676                 if (ctx->cache_ro)
2677                         cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2678                 else if (ctx->cache_rw)
2679                         cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2680         }
2681
2682         if (ctx->no_lease) {
2683                 if (ses->server->vals->protocol_id == 0) {
2684                         cifs_dbg(VFS,
2685                                 "SMB2 or later required for nolease option\n");
2686                         rc = -EOPNOTSUPP;
2687                         goto out_fail;
2688                 } else
2689                         tcon->no_lease = ctx->no_lease;
2690         }
2691
2692         /*
2693          * We can have only one retry value for a connection to a share so for
2694          * resources mounted more than once to the same server share the last
2695          * value passed in for the retry flag is used.
2696          */
2697         tcon->retry = ctx->retry;
2698         tcon->nocase = ctx->nocase;
2699         tcon->broken_sparse_sup = ctx->no_sparse;
2700         tcon->max_cached_dirs = ctx->max_cached_dirs;
2701         tcon->nodelete = ctx->nodelete;
2702         tcon->local_lease = ctx->local_lease;
2703         INIT_LIST_HEAD(&tcon->pending_opens);
2704         tcon->status = TID_GOOD;
2705
2706         INIT_DELAYED_WORK(&tcon->query_interfaces,
2707                           smb2_query_server_interfaces);
2708         if (ses->server->dialect >= SMB30_PROT_ID &&
2709             (ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
2710                 /* schedule query interfaces poll */
2711                 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
2712                                    (SMB_INTERFACE_POLL_INTERVAL * HZ));
2713         }
2714 #ifdef CONFIG_CIFS_DFS_UPCALL
2715         INIT_DELAYED_WORK(&tcon->dfs_cache_work, dfs_cache_refresh);
2716 #endif
2717         spin_lock(&cifs_tcp_ses_lock);
2718         list_add(&tcon->tcon_list, &ses->tcon_list);
2719         spin_unlock(&cifs_tcp_ses_lock);
2720
2721         return tcon;
2722
2723 out_fail:
2724         tconInfoFree(tcon);
2725         return ERR_PTR(rc);
2726 }
2727
2728 void
2729 cifs_put_tlink(struct tcon_link *tlink)
2730 {
2731         if (!tlink || IS_ERR(tlink))
2732                 return;
2733
2734         if (!atomic_dec_and_test(&tlink->tl_count) ||
2735             test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2736                 tlink->tl_time = jiffies;
2737                 return;
2738         }
2739
2740         if (!IS_ERR(tlink_tcon(tlink)))
2741                 cifs_put_tcon(tlink_tcon(tlink));
2742         kfree(tlink);
2743 }
2744
2745 static int
2746 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2747 {
2748         struct cifs_sb_info *old = CIFS_SB(sb);
2749         struct cifs_sb_info *new = mnt_data->cifs_sb;
2750         unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2751         unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2752
2753         if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2754                 return 0;
2755
2756         if (old->mnt_cifs_serverino_autodisabled)
2757                 newflags &= ~CIFS_MOUNT_SERVER_INUM;
2758
2759         if (oldflags != newflags)
2760                 return 0;
2761
2762         /*
2763          * We want to share sb only if we don't specify an r/wsize or
2764          * specified r/wsize is greater than or equal to existing one.
2765          */
2766         if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2767                 return 0;
2768
2769         if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2770                 return 0;
2771
2772         if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2773             !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2774                 return 0;
2775
2776         if (old->ctx->file_mode != new->ctx->file_mode ||
2777             old->ctx->dir_mode != new->ctx->dir_mode)
2778                 return 0;
2779
2780         if (strcmp(old->local_nls->charset, new->local_nls->charset))
2781                 return 0;
2782
2783         if (old->ctx->acregmax != new->ctx->acregmax)
2784                 return 0;
2785         if (old->ctx->acdirmax != new->ctx->acdirmax)
2786                 return 0;
2787         if (old->ctx->closetimeo != new->ctx->closetimeo)
2788                 return 0;
2789
2790         return 1;
2791 }
2792
2793 static int match_prepath(struct super_block *sb,
2794                          struct cifs_tcon *tcon,
2795                          struct cifs_mnt_data *mnt_data)
2796 {
2797         struct smb3_fs_context *ctx = mnt_data->ctx;
2798         struct cifs_sb_info *old = CIFS_SB(sb);
2799         struct cifs_sb_info *new = mnt_data->cifs_sb;
2800         bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2801                 old->prepath;
2802         bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2803                 new->prepath;
2804
2805         if (tcon->origin_fullpath &&
2806             dfs_src_pathname_equal(tcon->origin_fullpath, ctx->source))
2807                 return 1;
2808
2809         if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2810                 return 1;
2811         else if (!old_set && !new_set)
2812                 return 1;
2813
2814         return 0;
2815 }
2816
2817 int
2818 cifs_match_super(struct super_block *sb, void *data)
2819 {
2820         struct cifs_mnt_data *mnt_data = data;
2821         struct smb3_fs_context *ctx;
2822         struct cifs_sb_info *cifs_sb;
2823         struct TCP_Server_Info *tcp_srv;
2824         struct cifs_ses *ses;
2825         struct cifs_tcon *tcon;
2826         struct tcon_link *tlink;
2827         int rc = 0;
2828
2829         spin_lock(&cifs_tcp_ses_lock);
2830         cifs_sb = CIFS_SB(sb);
2831
2832         /* We do not want to use a superblock that has been shutdown */
2833         if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
2834                 spin_unlock(&cifs_tcp_ses_lock);
2835                 return 0;
2836         }
2837
2838         tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2839         if (IS_ERR_OR_NULL(tlink)) {
2840                 pr_warn_once("%s: skip super matching due to bad tlink(%p)\n",
2841                              __func__, tlink);
2842                 spin_unlock(&cifs_tcp_ses_lock);
2843                 return 0;
2844         }
2845         tcon = tlink_tcon(tlink);
2846         ses = tcon->ses;
2847         tcp_srv = ses->server;
2848
2849         ctx = mnt_data->ctx;
2850
2851         spin_lock(&tcp_srv->srv_lock);
2852         spin_lock(&ses->ses_lock);
2853         spin_lock(&ses->chan_lock);
2854         spin_lock(&tcon->tc_lock);
2855         if (!match_server(tcp_srv, ctx, true) ||
2856             !match_session(ses, ctx) ||
2857             !match_tcon(tcon, ctx) ||
2858             !match_prepath(sb, tcon, mnt_data)) {
2859                 rc = 0;
2860                 goto out;
2861         }
2862
2863         rc = compare_mount_options(sb, mnt_data);
2864 out:
2865         spin_unlock(&tcon->tc_lock);
2866         spin_unlock(&ses->chan_lock);
2867         spin_unlock(&ses->ses_lock);
2868         spin_unlock(&tcp_srv->srv_lock);
2869
2870         spin_unlock(&cifs_tcp_ses_lock);
2871         cifs_put_tlink(tlink);
2872         return rc;
2873 }
2874
2875 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2876 static struct lock_class_key cifs_key[2];
2877 static struct lock_class_key cifs_slock_key[2];
2878
2879 static inline void
2880 cifs_reclassify_socket4(struct socket *sock)
2881 {
2882         struct sock *sk = sock->sk;
2883
2884         BUG_ON(!sock_allow_reclassification(sk));
2885         sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2886                 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2887 }
2888
2889 static inline void
2890 cifs_reclassify_socket6(struct socket *sock)
2891 {
2892         struct sock *sk = sock->sk;
2893
2894         BUG_ON(!sock_allow_reclassification(sk));
2895         sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2896                 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2897 }
2898 #else
2899 static inline void
2900 cifs_reclassify_socket4(struct socket *sock)
2901 {
2902 }
2903
2904 static inline void
2905 cifs_reclassify_socket6(struct socket *sock)
2906 {
2907 }
2908 #endif
2909
2910 /* See RFC1001 section 14 on representation of Netbios names */
2911 static void rfc1002mangle(char *target, char *source, unsigned int length)
2912 {
2913         unsigned int i, j;
2914
2915         for (i = 0, j = 0; i < (length); i++) {
2916                 /* mask a nibble at a time and encode */
2917                 target[j] = 'A' + (0x0F & (source[i] >> 4));
2918                 target[j+1] = 'A' + (0x0F & source[i]);
2919                 j += 2;
2920         }
2921
2922 }
2923
2924 static int
2925 bind_socket(struct TCP_Server_Info *server)
2926 {
2927         int rc = 0;
2928
2929         if (server->srcaddr.ss_family != AF_UNSPEC) {
2930                 /* Bind to the specified local IP address */
2931                 struct socket *socket = server->ssocket;
2932
2933                 rc = kernel_bind(socket,
2934                                  (struct sockaddr *) &server->srcaddr,
2935                                  sizeof(server->srcaddr));
2936                 if (rc < 0) {
2937                         struct sockaddr_in *saddr4;
2938                         struct sockaddr_in6 *saddr6;
2939
2940                         saddr4 = (struct sockaddr_in *)&server->srcaddr;
2941                         saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2942                         if (saddr6->sin6_family == AF_INET6)
2943                                 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2944                                          &saddr6->sin6_addr, rc);
2945                         else
2946                                 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2947                                          &saddr4->sin_addr.s_addr, rc);
2948                 }
2949         }
2950         return rc;
2951 }
2952
2953 static int
2954 ip_rfc1001_connect(struct TCP_Server_Info *server)
2955 {
2956         int rc = 0;
2957         /*
2958          * some servers require RFC1001 sessinit before sending
2959          * negprot - BB check reconnection in case where second
2960          * sessinit is sent but no second negprot
2961          */
2962         struct rfc1002_session_packet req = {};
2963         struct smb_hdr *smb_buf = (struct smb_hdr *)&req;
2964         unsigned int len;
2965
2966         req.trailer.session_req.called_len = sizeof(req.trailer.session_req.called_name);
2967
2968         if (server->server_RFC1001_name[0] != 0)
2969                 rfc1002mangle(req.trailer.session_req.called_name,
2970                               server->server_RFC1001_name,
2971                               RFC1001_NAME_LEN_WITH_NULL);
2972         else
2973                 rfc1002mangle(req.trailer.session_req.called_name,
2974                               DEFAULT_CIFS_CALLED_NAME,
2975                               RFC1001_NAME_LEN_WITH_NULL);
2976
2977         req.trailer.session_req.calling_len = sizeof(req.trailer.session_req.calling_name);
2978
2979         /* calling name ends in null (byte 16) from old smb convention */
2980         if (server->workstation_RFC1001_name[0] != 0)
2981                 rfc1002mangle(req.trailer.session_req.calling_name,
2982                               server->workstation_RFC1001_name,
2983                               RFC1001_NAME_LEN_WITH_NULL);
2984         else
2985                 rfc1002mangle(req.trailer.session_req.calling_name,
2986                               "LINUX_CIFS_CLNT",
2987                               RFC1001_NAME_LEN_WITH_NULL);
2988
2989         /*
2990          * As per rfc1002, @len must be the number of bytes that follows the
2991          * length field of a rfc1002 session request payload.
2992          */
2993         len = sizeof(req) - offsetof(struct rfc1002_session_packet, trailer.session_req);
2994
2995         smb_buf->smb_buf_length = cpu_to_be32((RFC1002_SESSION_REQUEST << 24) | len);
2996         rc = smb_send(server, smb_buf, len);
2997         /*
2998          * RFC1001 layer in at least one server requires very short break before
2999          * negprot presumably because not expecting negprot to follow so fast.
3000          * This is a simple solution that works without complicating the code
3001          * and causes no significant slowing down on mount for everyone else
3002          */
3003         usleep_range(1000, 2000);
3004
3005         return rc;
3006 }
3007
3008 static int
3009 generic_ip_connect(struct TCP_Server_Info *server)
3010 {
3011         struct sockaddr *saddr;
3012         struct socket *socket;
3013         int slen, sfamily;
3014         __be16 sport;
3015         int rc = 0;
3016
3017         saddr = (struct sockaddr *) &server->dstaddr;
3018
3019         if (server->dstaddr.ss_family == AF_INET6) {
3020                 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
3021
3022                 sport = ipv6->sin6_port;
3023                 slen = sizeof(struct sockaddr_in6);
3024                 sfamily = AF_INET6;
3025                 cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
3026                                 ntohs(sport));
3027         } else {
3028                 struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
3029
3030                 sport = ipv4->sin_port;
3031                 slen = sizeof(struct sockaddr_in);
3032                 sfamily = AF_INET;
3033                 cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
3034                                 ntohs(sport));
3035         }
3036
3037         if (server->ssocket) {
3038                 socket = server->ssocket;
3039         } else {
3040                 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
3041                                    IPPROTO_TCP, &server->ssocket, 1);
3042                 if (rc < 0) {
3043                         cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
3044                         return rc;
3045                 }
3046
3047                 /* BB other socket options to set KEEPALIVE, NODELAY? */
3048                 cifs_dbg(FYI, "Socket created\n");
3049                 socket = server->ssocket;
3050                 socket->sk->sk_allocation = GFP_NOFS;
3051                 socket->sk->sk_use_task_frag = false;
3052                 if (sfamily == AF_INET6)
3053                         cifs_reclassify_socket6(socket);
3054                 else
3055                         cifs_reclassify_socket4(socket);
3056         }
3057
3058         rc = bind_socket(server);
3059         if (rc < 0)
3060                 return rc;
3061
3062         /*
3063          * Eventually check for other socket options to change from
3064          * the default. sock_setsockopt not used because it expects
3065          * user space buffer
3066          */
3067         socket->sk->sk_rcvtimeo = 7 * HZ;
3068         socket->sk->sk_sndtimeo = 5 * HZ;
3069
3070         /* make the bufsizes depend on wsize/rsize and max requests */
3071         if (server->noautotune) {
3072                 if (socket->sk->sk_sndbuf < (200 * 1024))
3073                         socket->sk->sk_sndbuf = 200 * 1024;
3074                 if (socket->sk->sk_rcvbuf < (140 * 1024))
3075                         socket->sk->sk_rcvbuf = 140 * 1024;
3076         }
3077
3078         if (server->tcp_nodelay)
3079                 tcp_sock_set_nodelay(socket->sk);
3080
3081         cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3082                  socket->sk->sk_sndbuf,
3083                  socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3084
3085         rc = kernel_connect(socket, saddr, slen,
3086                             server->noblockcnt ? O_NONBLOCK : 0);
3087         /*
3088          * When mounting SMB root file systems, we do not want to block in
3089          * connect. Otherwise bail out and then let cifs_reconnect() perform
3090          * reconnect failover - if possible.
3091          */
3092         if (server->noblockcnt && rc == -EINPROGRESS)
3093                 rc = 0;
3094         if (rc < 0) {
3095                 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3096                 trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
3097                 sock_release(socket);
3098                 server->ssocket = NULL;
3099                 return rc;
3100         }
3101         trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
3102         if (sport == htons(RFC1001_PORT))
3103                 rc = ip_rfc1001_connect(server);
3104
3105         return rc;
3106 }
3107
3108 static int
3109 ip_connect(struct TCP_Server_Info *server)
3110 {
3111         __be16 *sport;
3112         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3113         struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3114
3115         if (server->dstaddr.ss_family == AF_INET6)
3116                 sport = &addr6->sin6_port;
3117         else
3118                 sport = &addr->sin_port;
3119
3120         if (*sport == 0) {
3121                 int rc;
3122
3123                 /* try with 445 port at first */
3124                 *sport = htons(CIFS_PORT);
3125
3126                 rc = generic_ip_connect(server);
3127                 if (rc >= 0)
3128                         return rc;
3129
3130                 /* if it failed, try with 139 port */
3131                 *sport = htons(RFC1001_PORT);
3132         }
3133
3134         return generic_ip_connect(server);
3135 }
3136
3137 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3138 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3139                           struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3140 {
3141         /*
3142          * If we are reconnecting then should we check to see if
3143          * any requested capabilities changed locally e.g. via
3144          * remount but we can not do much about it here
3145          * if they have (even if we could detect it by the following)
3146          * Perhaps we could add a backpointer to array of sb from tcon
3147          * or if we change to make all sb to same share the same
3148          * sb as NFS - then we only have one backpointer to sb.
3149          * What if we wanted to mount the server share twice once with
3150          * and once without posixacls or posix paths?
3151          */
3152         __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3153
3154         if (ctx && ctx->no_linux_ext) {
3155                 tcon->fsUnixInfo.Capability = 0;
3156                 tcon->unix_ext = 0; /* Unix Extensions disabled */
3157                 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3158                 return;
3159         } else if (ctx)
3160                 tcon->unix_ext = 1; /* Unix Extensions supported */
3161
3162         if (!tcon->unix_ext) {
3163                 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3164                 return;
3165         }
3166
3167         if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3168                 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3169
3170                 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3171                 /*
3172                  * check for reconnect case in which we do not
3173                  * want to change the mount behavior if we can avoid it
3174                  */
3175                 if (ctx == NULL) {
3176                         /*
3177                          * turn off POSIX ACL and PATHNAMES if not set
3178                          * originally at mount time
3179                          */
3180                         if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3181                                 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3182                         if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3183                                 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3184                                         cifs_dbg(VFS, "POSIXPATH support change\n");
3185                                 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3186                         } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3187                                 cifs_dbg(VFS, "possible reconnect error\n");
3188                                 cifs_dbg(VFS, "server disabled POSIX path support\n");
3189                         }
3190                 }
3191
3192                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3193                         cifs_dbg(VFS, "per-share encryption not supported yet\n");
3194
3195                 cap &= CIFS_UNIX_CAP_MASK;
3196                 if (ctx && ctx->no_psx_acl)
3197                         cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3198                 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3199                         cifs_dbg(FYI, "negotiated posix acl support\n");
3200                         if (cifs_sb)
3201                                 cifs_sb->mnt_cifs_flags |=
3202                                         CIFS_MOUNT_POSIXACL;
3203                 }
3204
3205                 if (ctx && ctx->posix_paths == 0)
3206                         cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3207                 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3208                         cifs_dbg(FYI, "negotiate posix pathnames\n");
3209                         if (cifs_sb)
3210                                 cifs_sb->mnt_cifs_flags |=
3211                                         CIFS_MOUNT_POSIX_PATHS;
3212                 }
3213
3214                 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3215 #ifdef CONFIG_CIFS_DEBUG2
3216                 if (cap & CIFS_UNIX_FCNTL_CAP)
3217                         cifs_dbg(FYI, "FCNTL cap\n");
3218                 if (cap & CIFS_UNIX_EXTATTR_CAP)
3219                         cifs_dbg(FYI, "EXTATTR cap\n");
3220                 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3221                         cifs_dbg(FYI, "POSIX path cap\n");
3222                 if (cap & CIFS_UNIX_XATTR_CAP)
3223                         cifs_dbg(FYI, "XATTR cap\n");
3224                 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3225                         cifs_dbg(FYI, "POSIX ACL cap\n");
3226                 if (cap & CIFS_UNIX_LARGE_READ_CAP)
3227                         cifs_dbg(FYI, "very large read cap\n");
3228                 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3229                         cifs_dbg(FYI, "very large write cap\n");
3230                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3231                         cifs_dbg(FYI, "transport encryption cap\n");
3232                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3233                         cifs_dbg(FYI, "mandatory transport encryption cap\n");
3234 #endif /* CIFS_DEBUG2 */
3235                 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3236                         if (ctx == NULL)
3237                                 cifs_dbg(FYI, "resetting capabilities failed\n");
3238                         else
3239                                 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");
3240
3241                 }
3242         }
3243 }
3244 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3245
3246 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3247 {
3248         struct smb3_fs_context *ctx = cifs_sb->ctx;
3249
3250         INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3251
3252         spin_lock_init(&cifs_sb->tlink_tree_lock);
3253         cifs_sb->tlink_tree = RB_ROOT;
3254
3255         cifs_dbg(FYI, "file mode: %04ho  dir mode: %04ho\n",
3256                  ctx->file_mode, ctx->dir_mode);
3257
3258         /* this is needed for ASCII cp to Unicode converts */
3259         if (ctx->iocharset == NULL) {
3260                 /* load_nls_default cannot return null */
3261                 cifs_sb->local_nls = load_nls_default();
3262         } else {
3263                 cifs_sb->local_nls = load_nls(ctx->iocharset);
3264                 if (cifs_sb->local_nls == NULL) {
3265                         cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3266                                  ctx->iocharset);
3267                         return -ELIBACC;
3268                 }
3269         }
3270         ctx->local_nls = cifs_sb->local_nls;
3271
3272         smb3_update_mnt_flags(cifs_sb);
3273
3274         if (ctx->direct_io)
3275                 cifs_dbg(FYI, "mounting share using direct i/o\n");
3276         if (ctx->cache_ro) {
3277                 cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
3278                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3279         } else if (ctx->cache_rw) {
3280                 cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
3281                 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
3282                                             CIFS_MOUNT_RW_CACHE);
3283         }
3284
3285         if ((ctx->cifs_acl) && (ctx->dynperm))
3286                 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3287
3288         if (ctx->prepath) {
3289                 cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3290                 if (cifs_sb->prepath == NULL)
3291                         return -ENOMEM;
3292                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3293         }
3294
3295         return 0;
3296 }
3297
3298 /* Release all succeed connections */
3299 void cifs_mount_put_conns(struct cifs_mount_ctx *mnt_ctx)
3300 {
3301         int rc = 0;
3302
3303         if (mnt_ctx->tcon)
3304                 cifs_put_tcon(mnt_ctx->tcon);
3305         else if (mnt_ctx->ses)
3306                 cifs_put_smb_ses(mnt_ctx->ses);
3307         else if (mnt_ctx->server)
3308                 cifs_put_tcp_session(mnt_ctx->server, 0);
3309         mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3310         free_xid(mnt_ctx->xid);
3311 }
3312
3313 int cifs_mount_get_session(struct cifs_mount_ctx *mnt_ctx)
3314 {
3315         struct TCP_Server_Info *server = NULL;
3316         struct smb3_fs_context *ctx;
3317         struct cifs_ses *ses = NULL;
3318         unsigned int xid;
3319         int rc = 0;
3320
3321         xid = get_xid();
3322
3323         if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->fs_ctx)) {
3324                 rc = -EINVAL;
3325                 goto out;
3326         }
3327         ctx = mnt_ctx->fs_ctx;
3328
3329         /* get a reference to a tcp session */
3330         server = cifs_get_tcp_session(ctx, NULL);
3331         if (IS_ERR(server)) {
3332                 rc = PTR_ERR(server);
3333                 server = NULL;
3334                 goto out;
3335         }
3336
3337         /* get a reference to a SMB session */
3338         ses = cifs_get_smb_ses(server, ctx);
3339         if (IS_ERR(ses)) {
3340                 rc = PTR_ERR(ses);
3341                 ses = NULL;
3342                 goto out;
3343         }
3344
3345         if ((ctx->persistent == true) && (!(ses->server->capabilities &
3346                                             SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3347                 cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3348                 rc = -EOPNOTSUPP;
3349         }
3350
3351 out:
3352         mnt_ctx->xid = xid;
3353         mnt_ctx->server = server;
3354         mnt_ctx->ses = ses;
3355         mnt_ctx->tcon = NULL;
3356
3357         return rc;
3358 }
3359
3360 int cifs_mount_get_tcon(struct cifs_mount_ctx *mnt_ctx)
3361 {
3362         struct TCP_Server_Info *server;
3363         struct cifs_sb_info *cifs_sb;
3364         struct smb3_fs_context *ctx;
3365         struct cifs_tcon *tcon = NULL;
3366         int rc = 0;
3367
3368         if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->server || !mnt_ctx->ses || !mnt_ctx->fs_ctx ||
3369                          !mnt_ctx->cifs_sb)) {
3370                 rc = -EINVAL;
3371                 goto out;
3372         }
3373         server = mnt_ctx->server;
3374         ctx = mnt_ctx->fs_ctx;
3375         cifs_sb = mnt_ctx->cifs_sb;
3376
3377         /* search for existing tcon to this server share */
3378         tcon = cifs_get_tcon(mnt_ctx->ses, ctx);
3379         if (IS_ERR(tcon)) {
3380                 rc = PTR_ERR(tcon);
3381                 tcon = NULL;
3382                 goto out;
3383         }
3384
3385         /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3386         if (tcon->posix_extensions)
3387                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3388
3389 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3390         /* tell server which Unix caps we support */
3391         if (cap_unix(tcon->ses)) {
3392                 /*
3393                  * reset of caps checks mount to see if unix extensions disabled
3394                  * for just this mount.
3395                  */
3396                 reset_cifs_unix_caps(mnt_ctx->xid, tcon, cifs_sb, ctx);
3397                 spin_lock(&tcon->ses->server->srv_lock);
3398                 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3399                     (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3400                      CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3401                         spin_unlock(&tcon->ses->server->srv_lock);
3402                         rc = -EACCES;
3403                         goto out;
3404                 }
3405                 spin_unlock(&tcon->ses->server->srv_lock);
3406         } else
3407 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3408                 tcon->unix_ext = 0; /* server does not support them */
3409
3410         /* do not care if a following call succeed - informational */
3411         if (!tcon->pipe && server->ops->qfs_tcon) {
3412                 server->ops->qfs_tcon(mnt_ctx->xid, tcon, cifs_sb);
3413                 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3414                         if (tcon->fsDevInfo.DeviceCharacteristics &
3415                             cpu_to_le32(FILE_READ_ONLY_DEVICE))
3416                                 cifs_dbg(VFS, "mounted to read only share\n");
3417                         else if ((cifs_sb->mnt_cifs_flags &
3418                                   CIFS_MOUNT_RW_CACHE) == 0)
3419                                 cifs_dbg(VFS, "read only mount of RW share\n");
3420                         /* no need to log a RW mount of a typical RW share */
3421                 }
3422         }
3423
3424         /*
3425          * Clamp the rsize/wsize mount arguments if they are too big for the server
3426          * and set the rsize/wsize to the negotiated values if not passed in by
3427          * the user on mount
3428          */
3429         if ((cifs_sb->ctx->wsize == 0) ||
3430             (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
3431                 cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
3432         if ((cifs_sb->ctx->rsize == 0) ||
3433             (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3434                 cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3435
3436         /*
3437          * The cookie is initialized from volume info returned above.
3438          * Inside cifs_fscache_get_super_cookie it checks
3439          * that we do not get super cookie twice.
3440          */
3441         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
3442                 cifs_fscache_get_super_cookie(tcon);
3443
3444 out:
3445         mnt_ctx->tcon = tcon;
3446         return rc;
3447 }
3448
3449 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3450                              struct cifs_tcon *tcon)
3451 {
3452         struct tcon_link *tlink;
3453
3454         /* hang the tcon off of the superblock */
3455         tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3456         if (tlink == NULL)
3457                 return -ENOMEM;
3458
3459         tlink->tl_uid = ses->linux_uid;
3460         tlink->tl_tcon = tcon;
3461         tlink->tl_time = jiffies;
3462         set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3463         set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3464
3465         cifs_sb->master_tlink = tlink;
3466         spin_lock(&cifs_sb->tlink_tree_lock);
3467         tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3468         spin_unlock(&cifs_sb->tlink_tree_lock);
3469
3470         queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3471                                 TLINK_IDLE_EXPIRE);
3472         return 0;
3473 }
3474
3475 static int
3476 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3477                                         unsigned int xid,
3478                                         struct cifs_tcon *tcon,
3479                                         struct cifs_sb_info *cifs_sb,
3480                                         char *full_path,
3481                                         int added_treename)
3482 {
3483         int rc;
3484         char *s;
3485         char sep, tmp;
3486         int skip = added_treename ? 1 : 0;
3487
3488         sep = CIFS_DIR_SEP(cifs_sb);
3489         s = full_path;
3490
3491         rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3492         while (rc == 0) {
3493                 /* skip separators */
3494                 while (*s == sep)
3495                         s++;
3496                 if (!*s)
3497                         break;
3498                 /* next separator */
3499                 while (*s && *s != sep)
3500                         s++;
3501                 /*
3502                  * if the treename is added, we then have to skip the first
3503                  * part within the separators
3504                  */
3505                 if (skip) {
3506                         skip = 0;
3507                         continue;
3508                 }
3509                 /*
3510                  * temporarily null-terminate the path at the end of
3511                  * the current component
3512                  */
3513                 tmp = *s;
3514                 *s = 0;
3515                 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3516                                                      full_path);
3517                 *s = tmp;
3518         }
3519         return rc;
3520 }
3521
3522 /*
3523  * Check if path is remote (i.e. a DFS share).
3524  *
3525  * Return -EREMOTE if it is, otherwise 0 or -errno.
3526  */
3527 int cifs_is_path_remote(struct cifs_mount_ctx *mnt_ctx)
3528 {
3529         int rc;
3530         struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3531         struct TCP_Server_Info *server = mnt_ctx->server;
3532         unsigned int xid = mnt_ctx->xid;
3533         struct cifs_tcon *tcon = mnt_ctx->tcon;
3534         struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3535         char *full_path;
3536
3537         if (!server->ops->is_path_accessible)
3538                 return -EOPNOTSUPP;
3539
3540         /*
3541          * cifs_build_path_to_root works only when we have a valid tcon
3542          */
3543         full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3544                                             tcon->Flags & SMB_SHARE_IS_IN_DFS);
3545         if (full_path == NULL)
3546                 return -ENOMEM;
3547
3548         cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3549
3550         rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3551                                              full_path);
3552         if (rc != 0 && rc != -EREMOTE)
3553                 goto out;
3554
3555         if (rc != -EREMOTE) {
3556                 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3557                         cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3558                 if (rc != 0) {
3559                         cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3560                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3561                         rc = 0;
3562                 }
3563         }
3564
3565 out:
3566         kfree(full_path);
3567         return rc;
3568 }
3569
3570 #ifdef CONFIG_CIFS_DFS_UPCALL
3571 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3572 {
3573         struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3574         bool isdfs;
3575         int rc;
3576
3577         INIT_LIST_HEAD(&mnt_ctx.dfs_ses_list);
3578
3579         rc = dfs_mount_share(&mnt_ctx, &isdfs);
3580         if (rc)
3581                 goto error;
3582         if (!isdfs)
3583                 goto out;
3584
3585         /*
3586          * After reconnecting to a different server, unique ids won't match anymore, so we disable
3587          * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3588          */
3589         cifs_autodisable_serverino(cifs_sb);
3590         /*
3591          * Force the use of prefix path to support failover on DFS paths that resolve to targets
3592          * that have different prefix paths.
3593          */
3594         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3595         kfree(cifs_sb->prepath);
3596         cifs_sb->prepath = ctx->prepath;
3597         ctx->prepath = NULL;
3598
3599 out:
3600         cifs_try_adding_channels(mnt_ctx.ses);
3601         rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3602         if (rc)
3603                 goto error;
3604
3605         free_xid(mnt_ctx.xid);
3606         return rc;
3607
3608 error:
3609         dfs_put_root_smb_sessions(&mnt_ctx.dfs_ses_list);
3610         cifs_mount_put_conns(&mnt_ctx);
3611         return rc;
3612 }
3613 #else
3614 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3615 {
3616         int rc = 0;
3617         struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3618
3619         rc = cifs_mount_get_session(&mnt_ctx);
3620         if (rc)
3621                 goto error;
3622
3623         rc = cifs_mount_get_tcon(&mnt_ctx);
3624         if (rc)
3625                 goto error;
3626
3627         rc = cifs_is_path_remote(&mnt_ctx);
3628         if (rc == -EREMOTE)
3629                 rc = -EOPNOTSUPP;
3630         if (rc)
3631                 goto error;
3632
3633         rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3634         if (rc)
3635                 goto error;
3636
3637         free_xid(mnt_ctx.xid);
3638         return rc;
3639
3640 error:
3641         cifs_mount_put_conns(&mnt_ctx);
3642         return rc;
3643 }
3644 #endif
3645
3646 /*
3647  * Issue a TREE_CONNECT request.
3648  */
3649 int
3650 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3651          const char *tree, struct cifs_tcon *tcon,
3652          const struct nls_table *nls_codepage)
3653 {
3654         struct smb_hdr *smb_buffer;
3655         struct smb_hdr *smb_buffer_response;
3656         TCONX_REQ *pSMB;
3657         TCONX_RSP *pSMBr;
3658         unsigned char *bcc_ptr;
3659         int rc = 0;
3660         int length;
3661         __u16 bytes_left, count;
3662
3663         if (ses == NULL)
3664                 return -EIO;
3665
3666         smb_buffer = cifs_buf_get();
3667         if (smb_buffer == NULL)
3668                 return -ENOMEM;
3669
3670         smb_buffer_response = smb_buffer;
3671
3672         header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3673                         NULL /*no tid */, 4 /*wct */);
3674
3675         smb_buffer->Mid = get_next_mid(ses->server);
3676         smb_buffer->Uid = ses->Suid;
3677         pSMB = (TCONX_REQ *) smb_buffer;
3678         pSMBr = (TCONX_RSP *) smb_buffer_response;
3679
3680         pSMB->AndXCommand = 0xFF;
3681         pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3682         bcc_ptr = &pSMB->Password[0];
3683
3684         pSMB->PasswordLength = cpu_to_le16(1);  /* minimum */
3685         *bcc_ptr = 0; /* password is null byte */
3686         bcc_ptr++;              /* skip password */
3687         /* already aligned so no need to do it below */
3688
3689         if (ses->server->sign)
3690                 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3691
3692         if (ses->capabilities & CAP_STATUS32)
3693                 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3694
3695         if (ses->capabilities & CAP_DFS)
3696                 smb_buffer->Flags2 |= SMBFLG2_DFS;
3697
3698         if (ses->capabilities & CAP_UNICODE) {
3699                 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3700                 length =
3701                     cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3702                         6 /* max utf8 char length in bytes */ *
3703                         (/* server len*/ + 256 /* share len */), nls_codepage);
3704                 bcc_ptr += 2 * length;  /* convert num 16 bit words to bytes */
3705                 bcc_ptr += 2;   /* skip trailing null */
3706         } else {                /* ASCII */
3707                 strcpy(bcc_ptr, tree);
3708                 bcc_ptr += strlen(tree) + 1;
3709         }
3710         strcpy(bcc_ptr, "?????");
3711         bcc_ptr += strlen("?????");
3712         bcc_ptr += 1;
3713         count = bcc_ptr - &pSMB->Password[0];
3714         be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3715         pSMB->ByteCount = cpu_to_le16(count);
3716
3717         rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3718                          0);
3719
3720         /* above now done in SendReceive */
3721         if (rc == 0) {
3722                 bool is_unicode;
3723
3724                 tcon->tid = smb_buffer_response->Tid;
3725                 bcc_ptr = pByteArea(smb_buffer_response);
3726                 bytes_left = get_bcc(smb_buffer_response);
3727                 length = strnlen(bcc_ptr, bytes_left - 2);
3728                 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3729                         is_unicode = true;
3730                 else
3731                         is_unicode = false;
3732
3733
3734                 /* skip service field (NB: this field is always ASCII) */
3735                 if (length == 3) {
3736                         if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3737                             (bcc_ptr[2] == 'C')) {
3738                                 cifs_dbg(FYI, "IPC connection\n");
3739                                 tcon->ipc = true;
3740                                 tcon->pipe = true;
3741                         }
3742                 } else if (length == 2) {
3743                         if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3744                                 /* the most common case */
3745                                 cifs_dbg(FYI, "disk share connection\n");
3746                         }
3747                 }
3748                 bcc_ptr += length + 1;
3749                 bytes_left -= (length + 1);
3750                 strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
3751
3752                 /* mostly informational -- no need to fail on error here */
3753                 kfree(tcon->nativeFileSystem);
3754                 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3755                                                       bytes_left, is_unicode,
3756                                                       nls_codepage);
3757
3758                 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3759
3760                 if ((smb_buffer_response->WordCount == 3) ||
3761                          (smb_buffer_response->WordCount == 7))
3762                         /* field is in same location */
3763                         tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3764                 else
3765                         tcon->Flags = 0;
3766                 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3767         }
3768
3769         cifs_buf_release(smb_buffer);
3770         return rc;
3771 }
3772
3773 static void delayed_free(struct rcu_head *p)
3774 {
3775         struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
3776
3777         unload_nls(cifs_sb->local_nls);
3778         smb3_cleanup_fs_context(cifs_sb->ctx);
3779         kfree(cifs_sb);
3780 }
3781
3782 void
3783 cifs_umount(struct cifs_sb_info *cifs_sb)
3784 {
3785         struct rb_root *root = &cifs_sb->tlink_tree;
3786         struct rb_node *node;
3787         struct tcon_link *tlink;
3788
3789         cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3790
3791         spin_lock(&cifs_sb->tlink_tree_lock);
3792         while ((node = rb_first(root))) {
3793                 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3794                 cifs_get_tlink(tlink);
3795                 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3796                 rb_erase(node, root);
3797
3798                 spin_unlock(&cifs_sb->tlink_tree_lock);
3799                 cifs_put_tlink(tlink);
3800                 spin_lock(&cifs_sb->tlink_tree_lock);
3801         }
3802         spin_unlock(&cifs_sb->tlink_tree_lock);
3803
3804         kfree(cifs_sb->prepath);
3805         call_rcu(&cifs_sb->rcu, delayed_free);
3806 }
3807
3808 int
3809 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
3810                         struct TCP_Server_Info *server)
3811 {
3812         int rc = 0;
3813
3814         if (!server->ops->need_neg || !server->ops->negotiate)
3815                 return -ENOSYS;
3816
3817         /* only send once per connect */
3818         spin_lock(&server->srv_lock);
3819         if (server->tcpStatus != CifsGood &&
3820             server->tcpStatus != CifsNew &&
3821             server->tcpStatus != CifsNeedNegotiate) {
3822                 spin_unlock(&server->srv_lock);
3823                 return -EHOSTDOWN;
3824         }
3825
3826         if (!server->ops->need_neg(server) &&
3827             server->tcpStatus == CifsGood) {
3828                 spin_unlock(&server->srv_lock);
3829                 return 0;
3830         }
3831
3832         server->tcpStatus = CifsInNegotiate;
3833         spin_unlock(&server->srv_lock);
3834
3835         rc = server->ops->negotiate(xid, ses, server);
3836         if (rc == 0) {
3837                 spin_lock(&server->srv_lock);
3838                 if (server->tcpStatus == CifsInNegotiate)
3839                         server->tcpStatus = CifsGood;
3840                 else
3841                         rc = -EHOSTDOWN;
3842                 spin_unlock(&server->srv_lock);
3843         } else {
3844                 spin_lock(&server->srv_lock);
3845                 if (server->tcpStatus == CifsInNegotiate)
3846                         server->tcpStatus = CifsNeedNegotiate;
3847                 spin_unlock(&server->srv_lock);
3848         }
3849
3850         return rc;
3851 }
3852
3853 int
3854 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
3855                    struct TCP_Server_Info *server,
3856                    struct nls_table *nls_info)
3857 {
3858         int rc = -ENOSYS;
3859         struct TCP_Server_Info *pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
3860         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&pserver->dstaddr;
3861         struct sockaddr_in *addr = (struct sockaddr_in *)&pserver->dstaddr;
3862         bool is_binding = false;
3863
3864         spin_lock(&ses->ses_lock);
3865         cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
3866                  __func__, ses->chans_need_reconnect);
3867
3868         if (ses->ses_status != SES_GOOD &&
3869             ses->ses_status != SES_NEW &&
3870             ses->ses_status != SES_NEED_RECON) {
3871                 spin_unlock(&ses->ses_lock);
3872                 return -EHOSTDOWN;
3873         }
3874
3875         /* only send once per connect */
3876         spin_lock(&ses->chan_lock);
3877         if (CIFS_ALL_CHANS_GOOD(ses)) {
3878                 if (ses->ses_status == SES_NEED_RECON)
3879                         ses->ses_status = SES_GOOD;
3880                 spin_unlock(&ses->chan_lock);
3881                 spin_unlock(&ses->ses_lock);
3882                 return 0;
3883         }
3884
3885         cifs_chan_set_in_reconnect(ses, server);
3886         is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
3887         spin_unlock(&ses->chan_lock);
3888
3889         if (!is_binding) {
3890                 ses->ses_status = SES_IN_SETUP;
3891
3892                 /* force iface_list refresh */
3893                 ses->iface_last_update = 0;
3894         }
3895         spin_unlock(&ses->ses_lock);
3896
3897         /* update ses ip_addr only for primary chan */
3898         if (server == pserver) {
3899                 if (server->dstaddr.ss_family == AF_INET6)
3900                         scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
3901                 else
3902                         scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
3903         }
3904
3905         if (!is_binding) {
3906                 ses->capabilities = server->capabilities;
3907                 if (!linuxExtEnabled)
3908                         ses->capabilities &= (~server->vals->cap_unix);
3909
3910                 if (ses->auth_key.response) {
3911                         cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
3912                                  ses->auth_key.response);
3913                         kfree_sensitive(ses->auth_key.response);
3914                         ses->auth_key.response = NULL;
3915                         ses->auth_key.len = 0;
3916                 }
3917         }
3918
3919         cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
3920                  server->sec_mode, server->capabilities, server->timeAdj);
3921
3922         if (server->ops->sess_setup)
3923                 rc = server->ops->sess_setup(xid, ses, server, nls_info);
3924
3925         if (rc) {
3926                 cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
3927                 spin_lock(&ses->ses_lock);
3928                 if (ses->ses_status == SES_IN_SETUP)
3929                         ses->ses_status = SES_NEED_RECON;
3930                 spin_lock(&ses->chan_lock);
3931                 cifs_chan_clear_in_reconnect(ses, server);
3932                 spin_unlock(&ses->chan_lock);
3933                 spin_unlock(&ses->ses_lock);
3934         } else {
3935                 spin_lock(&ses->ses_lock);
3936                 if (ses->ses_status == SES_IN_SETUP)
3937                         ses->ses_status = SES_GOOD;
3938                 spin_lock(&ses->chan_lock);
3939                 cifs_chan_clear_in_reconnect(ses, server);
3940                 cifs_chan_clear_need_reconnect(ses, server);
3941                 spin_unlock(&ses->chan_lock);
3942                 spin_unlock(&ses->ses_lock);
3943         }
3944
3945         return rc;
3946 }
3947
3948 static int
3949 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
3950 {
3951         ctx->sectype = ses->sectype;
3952
3953         /* krb5 is special, since we don't need username or pw */
3954         if (ctx->sectype == Kerberos)
3955                 return 0;
3956
3957         return cifs_set_cifscreds(ctx, ses);
3958 }
3959
3960 static struct cifs_tcon *
3961 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
3962 {
3963         int rc;
3964         struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
3965         struct cifs_ses *ses;
3966         struct cifs_tcon *tcon = NULL;
3967         struct smb3_fs_context *ctx;
3968
3969         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3970         if (ctx == NULL)
3971                 return ERR_PTR(-ENOMEM);
3972
3973         ctx->local_nls = cifs_sb->local_nls;
3974         ctx->linux_uid = fsuid;
3975         ctx->cred_uid = fsuid;
3976         ctx->UNC = master_tcon->tree_name;
3977         ctx->retry = master_tcon->retry;
3978         ctx->nocase = master_tcon->nocase;
3979         ctx->nohandlecache = master_tcon->nohandlecache;
3980         ctx->local_lease = master_tcon->local_lease;
3981         ctx->no_lease = master_tcon->no_lease;
3982         ctx->resilient = master_tcon->use_resilient;
3983         ctx->persistent = master_tcon->use_persistent;
3984         ctx->handle_timeout = master_tcon->handle_timeout;
3985         ctx->no_linux_ext = !master_tcon->unix_ext;
3986         ctx->linux_ext = master_tcon->posix_extensions;
3987         ctx->sectype = master_tcon->ses->sectype;
3988         ctx->sign = master_tcon->ses->sign;
3989         ctx->seal = master_tcon->seal;
3990         ctx->witness = master_tcon->use_witness;
3991
3992         rc = cifs_set_vol_auth(ctx, master_tcon->ses);
3993         if (rc) {
3994                 tcon = ERR_PTR(rc);
3995                 goto out;
3996         }
3997
3998         /* get a reference for the same TCP session */
3999         spin_lock(&cifs_tcp_ses_lock);
4000         ++master_tcon->ses->server->srv_count;
4001         spin_unlock(&cifs_tcp_ses_lock);
4002
4003         ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4004         if (IS_ERR(ses)) {
4005                 tcon = (struct cifs_tcon *)ses;
4006                 cifs_put_tcp_session(master_tcon->ses->server, 0);
4007                 goto out;
4008         }
4009
4010         tcon = cifs_get_tcon(ses, ctx);
4011         if (IS_ERR(tcon)) {
4012                 cifs_put_smb_ses(ses);
4013                 goto out;
4014         }
4015
4016 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4017         if (cap_unix(ses))
4018                 reset_cifs_unix_caps(0, tcon, NULL, ctx);
4019 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4020
4021 out:
4022         kfree(ctx->username);
4023         kfree_sensitive(ctx->password);
4024         kfree(ctx);
4025
4026         return tcon;
4027 }
4028
4029 struct cifs_tcon *
4030 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4031 {
4032         return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4033 }
4034
4035 /* find and return a tlink with given uid */
4036 static struct tcon_link *
4037 tlink_rb_search(struct rb_root *root, kuid_t uid)
4038 {
4039         struct rb_node *node = root->rb_node;
4040         struct tcon_link *tlink;
4041
4042         while (node) {
4043                 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4044
4045                 if (uid_gt(tlink->tl_uid, uid))
4046                         node = node->rb_left;
4047                 else if (uid_lt(tlink->tl_uid, uid))
4048                         node = node->rb_right;
4049                 else
4050                         return tlink;
4051         }
4052         return NULL;
4053 }
4054
4055 /* insert a tcon_link into the tree */
4056 static void
4057 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4058 {
4059         struct rb_node **new = &(root->rb_node), *parent = NULL;
4060         struct tcon_link *tlink;
4061
4062         while (*new) {
4063                 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4064                 parent = *new;
4065
4066                 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4067                         new = &((*new)->rb_left);
4068                 else
4069                         new = &((*new)->rb_right);
4070         }
4071
4072         rb_link_node(&new_tlink->tl_rbnode, parent, new);
4073         rb_insert_color(&new_tlink->tl_rbnode, root);
4074 }
4075
4076 /*
4077  * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4078  * current task.
4079  *
4080  * If the superblock doesn't refer to a multiuser mount, then just return
4081  * the master tcon for the mount.
4082  *
4083  * First, search the rbtree for an existing tcon for this fsuid. If one
4084  * exists, then check to see if it's pending construction. If it is then wait
4085  * for construction to complete. Once it's no longer pending, check to see if
4086  * it failed and either return an error or retry construction, depending on
4087  * the timeout.
4088  *
4089  * If one doesn't exist then insert a new tcon_link struct into the tree and
4090  * try to construct a new one.
4091  */
4092 struct tcon_link *
4093 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4094 {
4095         int ret;
4096         kuid_t fsuid = current_fsuid();
4097         struct tcon_link *tlink, *newtlink;
4098
4099         if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4100                 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4101
4102         spin_lock(&cifs_sb->tlink_tree_lock);
4103         tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4104         if (tlink)
4105                 cifs_get_tlink(tlink);
4106         spin_unlock(&cifs_sb->tlink_tree_lock);
4107
4108         if (tlink == NULL) {
4109                 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4110                 if (newtlink == NULL)
4111                         return ERR_PTR(-ENOMEM);
4112                 newtlink->tl_uid = fsuid;
4113                 newtlink->tl_tcon = ERR_PTR(-EACCES);
4114                 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4115                 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4116                 cifs_get_tlink(newtlink);
4117
4118                 spin_lock(&cifs_sb->tlink_tree_lock);
4119                 /* was one inserted after previous search? */
4120                 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4121                 if (tlink) {
4122                         cifs_get_tlink(tlink);
4123                         spin_unlock(&cifs_sb->tlink_tree_lock);
4124                         kfree(newtlink);
4125                         goto wait_for_construction;
4126                 }
4127                 tlink = newtlink;
4128                 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4129                 spin_unlock(&cifs_sb->tlink_tree_lock);
4130         } else {
4131 wait_for_construction:
4132                 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4133                                   TASK_INTERRUPTIBLE);
4134                 if (ret) {
4135                         cifs_put_tlink(tlink);
4136                         return ERR_PTR(-ERESTARTSYS);
4137                 }
4138
4139                 /* if it's good, return it */
4140                 if (!IS_ERR(tlink->tl_tcon))
4141                         return tlink;
4142
4143                 /* return error if we tried this already recently */
4144                 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4145                         cifs_put_tlink(tlink);
4146                         return ERR_PTR(-EACCES);
4147                 }
4148
4149                 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4150                         goto wait_for_construction;
4151         }
4152
4153         tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4154         clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4155         wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4156
4157         if (IS_ERR(tlink->tl_tcon)) {
4158                 cifs_put_tlink(tlink);
4159                 return ERR_PTR(-EACCES);
4160         }
4161
4162         return tlink;
4163 }
4164
4165 /*
4166  * periodic workqueue job that scans tcon_tree for a superblock and closes
4167  * out tcons.
4168  */
4169 static void
4170 cifs_prune_tlinks(struct work_struct *work)
4171 {
4172         struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4173                                                     prune_tlinks.work);
4174         struct rb_root *root = &cifs_sb->tlink_tree;
4175         struct rb_node *node;
4176         struct rb_node *tmp;
4177         struct tcon_link *tlink;
4178
4179         /*
4180          * Because we drop the spinlock in the loop in order to put the tlink
4181          * it's not guarded against removal of links from the tree. The only
4182          * places that remove entries from the tree are this function and
4183          * umounts. Because this function is non-reentrant and is canceled
4184          * before umount can proceed, this is safe.
4185          */
4186         spin_lock(&cifs_sb->tlink_tree_lock);
4187         node = rb_first(root);
4188         while (node != NULL) {
4189                 tmp = node;
4190                 node = rb_next(tmp);
4191                 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4192
4193                 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4194                     atomic_read(&tlink->tl_count) != 0 ||
4195                     time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4196                         continue;
4197
4198                 cifs_get_tlink(tlink);
4199                 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4200                 rb_erase(tmp, root);
4201
4202                 spin_unlock(&cifs_sb->tlink_tree_lock);
4203                 cifs_put_tlink(tlink);
4204                 spin_lock(&cifs_sb->tlink_tree_lock);
4205         }
4206         spin_unlock(&cifs_sb->tlink_tree_lock);
4207
4208         queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4209                                 TLINK_IDLE_EXPIRE);
4210 }
4211
4212 #ifndef CONFIG_CIFS_DFS_UPCALL
4213 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4214 {
4215         int rc;
4216         const struct smb_version_operations *ops = tcon->ses->server->ops;
4217
4218         /* only send once per connect */
4219         spin_lock(&tcon->tc_lock);
4220         if (tcon->status == TID_GOOD) {
4221                 spin_unlock(&tcon->tc_lock);
4222                 return 0;
4223         }
4224
4225         if (tcon->status != TID_NEW &&
4226             tcon->status != TID_NEED_TCON) {
4227                 spin_unlock(&tcon->tc_lock);
4228                 return -EHOSTDOWN;
4229         }
4230
4231         tcon->status = TID_IN_TCON;
4232         spin_unlock(&tcon->tc_lock);
4233
4234         rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name, tcon, nlsc);
4235         if (rc) {
4236                 spin_lock(&tcon->tc_lock);
4237                 if (tcon->status == TID_IN_TCON)
4238                         tcon->status = TID_NEED_TCON;
4239                 spin_unlock(&tcon->tc_lock);
4240         } else {
4241                 spin_lock(&tcon->tc_lock);
4242                 if (tcon->status == TID_IN_TCON)
4243                         tcon->status = TID_GOOD;
4244                 tcon->need_reconnect = false;
4245                 spin_unlock(&tcon->tc_lock);
4246         }
4247
4248         return rc;
4249 }
4250 #endif