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