GNU Linux-libre 6.8.7-gnu
[releases.git] / fs / smb / client / misc.c
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2008
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  */
8
9 #include <linux/slab.h>
10 #include <linux/ctype.h>
11 #include <linux/mempool.h>
12 #include <linux/vmalloc.h>
13 #include "cifspdu.h"
14 #include "cifsglob.h"
15 #include "cifsproto.h"
16 #include "cifs_debug.h"
17 #include "smberr.h"
18 #include "nterr.h"
19 #include "cifs_unicode.h"
20 #include "smb2pdu.h"
21 #include "cifsfs.h"
22 #ifdef CONFIG_CIFS_DFS_UPCALL
23 #include "dns_resolve.h"
24 #include "dfs_cache.h"
25 #include "dfs.h"
26 #endif
27 #include "fs_context.h"
28 #include "cached_dir.h"
29
30 extern mempool_t *cifs_sm_req_poolp;
31 extern mempool_t *cifs_req_poolp;
32
33 /* The xid serves as a useful identifier for each incoming vfs request,
34    in a similar way to the mid which is useful to track each sent smb,
35    and CurrentXid can also provide a running counter (although it
36    will eventually wrap past zero) of the total vfs operations handled
37    since the cifs fs was mounted */
38
39 unsigned int
40 _get_xid(void)
41 {
42         unsigned int xid;
43
44         spin_lock(&GlobalMid_Lock);
45         GlobalTotalActiveXid++;
46
47         /* keep high water mark for number of simultaneous ops in filesystem */
48         if (GlobalTotalActiveXid > GlobalMaxActiveXid)
49                 GlobalMaxActiveXid = GlobalTotalActiveXid;
50         if (GlobalTotalActiveXid > 65000)
51                 cifs_dbg(FYI, "warning: more than 65000 requests active\n");
52         xid = GlobalCurrentXid++;
53         spin_unlock(&GlobalMid_Lock);
54         return xid;
55 }
56
57 void
58 _free_xid(unsigned int xid)
59 {
60         spin_lock(&GlobalMid_Lock);
61         /* if (GlobalTotalActiveXid == 0)
62                 BUG(); */
63         GlobalTotalActiveXid--;
64         spin_unlock(&GlobalMid_Lock);
65 }
66
67 struct cifs_ses *
68 sesInfoAlloc(void)
69 {
70         struct cifs_ses *ret_buf;
71
72         ret_buf = kzalloc(sizeof(struct cifs_ses), GFP_KERNEL);
73         if (ret_buf) {
74                 atomic_inc(&sesInfoAllocCount);
75                 spin_lock_init(&ret_buf->ses_lock);
76                 ret_buf->ses_status = SES_NEW;
77                 ++ret_buf->ses_count;
78                 INIT_LIST_HEAD(&ret_buf->smb_ses_list);
79                 INIT_LIST_HEAD(&ret_buf->tcon_list);
80                 mutex_init(&ret_buf->session_mutex);
81                 spin_lock_init(&ret_buf->iface_lock);
82                 INIT_LIST_HEAD(&ret_buf->iface_list);
83                 spin_lock_init(&ret_buf->chan_lock);
84         }
85         return ret_buf;
86 }
87
88 void
89 sesInfoFree(struct cifs_ses *buf_to_free)
90 {
91         struct cifs_server_iface *iface = NULL, *niface = NULL;
92
93         if (buf_to_free == NULL) {
94                 cifs_dbg(FYI, "Null buffer passed to sesInfoFree\n");
95                 return;
96         }
97
98         unload_nls(buf_to_free->local_nls);
99         atomic_dec(&sesInfoAllocCount);
100         kfree(buf_to_free->serverOS);
101         kfree(buf_to_free->serverDomain);
102         kfree(buf_to_free->serverNOS);
103         kfree_sensitive(buf_to_free->password);
104         kfree(buf_to_free->user_name);
105         kfree(buf_to_free->domainName);
106         kfree_sensitive(buf_to_free->auth_key.response);
107         spin_lock(&buf_to_free->iface_lock);
108         list_for_each_entry_safe(iface, niface, &buf_to_free->iface_list,
109                                  iface_head)
110                 kref_put(&iface->refcount, release_iface);
111         spin_unlock(&buf_to_free->iface_lock);
112         kfree_sensitive(buf_to_free);
113 }
114
115 struct cifs_tcon *
116 tcon_info_alloc(bool dir_leases_enabled)
117 {
118         struct cifs_tcon *ret_buf;
119
120         ret_buf = kzalloc(sizeof(*ret_buf), GFP_KERNEL);
121         if (!ret_buf)
122                 return NULL;
123
124         if (dir_leases_enabled == true) {
125                 ret_buf->cfids = init_cached_dirs();
126                 if (!ret_buf->cfids) {
127                         kfree(ret_buf);
128                         return NULL;
129                 }
130         }
131         /* else ret_buf->cfids is already set to NULL above */
132
133         atomic_inc(&tconInfoAllocCount);
134         ret_buf->status = TID_NEW;
135         ++ret_buf->tc_count;
136         spin_lock_init(&ret_buf->tc_lock);
137         INIT_LIST_HEAD(&ret_buf->openFileList);
138         INIT_LIST_HEAD(&ret_buf->tcon_list);
139         spin_lock_init(&ret_buf->open_file_lock);
140         spin_lock_init(&ret_buf->stat_lock);
141         atomic_set(&ret_buf->num_local_opens, 0);
142         atomic_set(&ret_buf->num_remote_opens, 0);
143         ret_buf->stats_from_time = ktime_get_real_seconds();
144
145         return ret_buf;
146 }
147
148 void
149 tconInfoFree(struct cifs_tcon *tcon)
150 {
151         if (tcon == NULL) {
152                 cifs_dbg(FYI, "Null buffer passed to tconInfoFree\n");
153                 return;
154         }
155         free_cached_dirs(tcon->cfids);
156         atomic_dec(&tconInfoAllocCount);
157         kfree(tcon->nativeFileSystem);
158         kfree_sensitive(tcon->password);
159         kfree(tcon->origin_fullpath);
160         kfree(tcon);
161 }
162
163 struct smb_hdr *
164 cifs_buf_get(void)
165 {
166         struct smb_hdr *ret_buf = NULL;
167         /*
168          * SMB2 header is bigger than CIFS one - no problems to clean some
169          * more bytes for CIFS.
170          */
171         size_t buf_size = sizeof(struct smb2_hdr);
172
173         /*
174          * We could use negotiated size instead of max_msgsize -
175          * but it may be more efficient to always alloc same size
176          * albeit slightly larger than necessary and maxbuffersize
177          * defaults to this and can not be bigger.
178          */
179         ret_buf = mempool_alloc(cifs_req_poolp, GFP_NOFS);
180
181         /* clear the first few header bytes */
182         /* for most paths, more is cleared in header_assemble */
183         memset(ret_buf, 0, buf_size + 3);
184         atomic_inc(&buf_alloc_count);
185 #ifdef CONFIG_CIFS_STATS2
186         atomic_inc(&total_buf_alloc_count);
187 #endif /* CONFIG_CIFS_STATS2 */
188
189         return ret_buf;
190 }
191
192 void
193 cifs_buf_release(void *buf_to_free)
194 {
195         if (buf_to_free == NULL) {
196                 /* cifs_dbg(FYI, "Null buffer passed to cifs_buf_release\n");*/
197                 return;
198         }
199         mempool_free(buf_to_free, cifs_req_poolp);
200
201         atomic_dec(&buf_alloc_count);
202         return;
203 }
204
205 struct smb_hdr *
206 cifs_small_buf_get(void)
207 {
208         struct smb_hdr *ret_buf = NULL;
209
210 /* We could use negotiated size instead of max_msgsize -
211    but it may be more efficient to always alloc same size
212    albeit slightly larger than necessary and maxbuffersize
213    defaults to this and can not be bigger */
214         ret_buf = mempool_alloc(cifs_sm_req_poolp, GFP_NOFS);
215         /* No need to clear memory here, cleared in header assemble */
216         /*      memset(ret_buf, 0, sizeof(struct smb_hdr) + 27);*/
217         atomic_inc(&small_buf_alloc_count);
218 #ifdef CONFIG_CIFS_STATS2
219         atomic_inc(&total_small_buf_alloc_count);
220 #endif /* CONFIG_CIFS_STATS2 */
221
222         return ret_buf;
223 }
224
225 void
226 cifs_small_buf_release(void *buf_to_free)
227 {
228
229         if (buf_to_free == NULL) {
230                 cifs_dbg(FYI, "Null buffer passed to cifs_small_buf_release\n");
231                 return;
232         }
233         mempool_free(buf_to_free, cifs_sm_req_poolp);
234
235         atomic_dec(&small_buf_alloc_count);
236         return;
237 }
238
239 void
240 free_rsp_buf(int resp_buftype, void *rsp)
241 {
242         if (resp_buftype == CIFS_SMALL_BUFFER)
243                 cifs_small_buf_release(rsp);
244         else if (resp_buftype == CIFS_LARGE_BUFFER)
245                 cifs_buf_release(rsp);
246 }
247
248 /* NB: MID can not be set if treeCon not passed in, in that
249    case it is responsbility of caller to set the mid */
250 void
251 header_assemble(struct smb_hdr *buffer, char smb_command /* command */ ,
252                 const struct cifs_tcon *treeCon, int word_count
253                 /* length of fixed section (word count) in two byte units  */)
254 {
255         char *temp = (char *) buffer;
256
257         memset(temp, 0, 256); /* bigger than MAX_CIFS_HDR_SIZE */
258
259         buffer->smb_buf_length = cpu_to_be32(
260             (2 * word_count) + sizeof(struct smb_hdr) -
261             4 /*  RFC 1001 length field does not count */  +
262             2 /* for bcc field itself */) ;
263
264         buffer->Protocol[0] = 0xFF;
265         buffer->Protocol[1] = 'S';
266         buffer->Protocol[2] = 'M';
267         buffer->Protocol[3] = 'B';
268         buffer->Command = smb_command;
269         buffer->Flags = 0x00;   /* case sensitive */
270         buffer->Flags2 = SMBFLG2_KNOWS_LONG_NAMES;
271         buffer->Pid = cpu_to_le16((__u16)current->tgid);
272         buffer->PidHigh = cpu_to_le16((__u16)(current->tgid >> 16));
273         if (treeCon) {
274                 buffer->Tid = treeCon->tid;
275                 if (treeCon->ses) {
276                         if (treeCon->ses->capabilities & CAP_UNICODE)
277                                 buffer->Flags2 |= SMBFLG2_UNICODE;
278                         if (treeCon->ses->capabilities & CAP_STATUS32)
279                                 buffer->Flags2 |= SMBFLG2_ERR_STATUS;
280
281                         /* Uid is not converted */
282                         buffer->Uid = treeCon->ses->Suid;
283                         if (treeCon->ses->server)
284                                 buffer->Mid = get_next_mid(treeCon->ses->server);
285                 }
286                 if (treeCon->Flags & SMB_SHARE_IS_IN_DFS)
287                         buffer->Flags2 |= SMBFLG2_DFS;
288                 if (treeCon->nocase)
289                         buffer->Flags  |= SMBFLG_CASELESS;
290                 if ((treeCon->ses) && (treeCon->ses->server))
291                         if (treeCon->ses->server->sign)
292                                 buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
293         }
294
295 /*  endian conversion of flags is now done just before sending */
296         buffer->WordCount = (char) word_count;
297         return;
298 }
299
300 static int
301 check_smb_hdr(struct smb_hdr *smb)
302 {
303         /* does it have the right SMB "signature" ? */
304         if (*(__le32 *) smb->Protocol != cpu_to_le32(0x424d53ff)) {
305                 cifs_dbg(VFS, "Bad protocol string signature header 0x%x\n",
306                          *(unsigned int *)smb->Protocol);
307                 return 1;
308         }
309
310         /* if it's a response then accept */
311         if (smb->Flags & SMBFLG_RESPONSE)
312                 return 0;
313
314         /* only one valid case where server sends us request */
315         if (smb->Command == SMB_COM_LOCKING_ANDX)
316                 return 0;
317
318         cifs_dbg(VFS, "Server sent request, not response. mid=%u\n",
319                  get_mid(smb));
320         return 1;
321 }
322
323 int
324 checkSMB(char *buf, unsigned int total_read, struct TCP_Server_Info *server)
325 {
326         struct smb_hdr *smb = (struct smb_hdr *)buf;
327         __u32 rfclen = be32_to_cpu(smb->smb_buf_length);
328         __u32 clc_len;  /* calculated length */
329         cifs_dbg(FYI, "checkSMB Length: 0x%x, smb_buf_length: 0x%x\n",
330                  total_read, rfclen);
331
332         /* is this frame too small to even get to a BCC? */
333         if (total_read < 2 + sizeof(struct smb_hdr)) {
334                 if ((total_read >= sizeof(struct smb_hdr) - 1)
335                             && (smb->Status.CifsError != 0)) {
336                         /* it's an error return */
337                         smb->WordCount = 0;
338                         /* some error cases do not return wct and bcc */
339                         return 0;
340                 } else if ((total_read == sizeof(struct smb_hdr) + 1) &&
341                                 (smb->WordCount == 0)) {
342                         char *tmp = (char *)smb;
343                         /* Need to work around a bug in two servers here */
344                         /* First, check if the part of bcc they sent was zero */
345                         if (tmp[sizeof(struct smb_hdr)] == 0) {
346                                 /* some servers return only half of bcc
347                                  * on simple responses (wct, bcc both zero)
348                                  * in particular have seen this on
349                                  * ulogoffX and FindClose. This leaves
350                                  * one byte of bcc potentially unitialized
351                                  */
352                                 /* zero rest of bcc */
353                                 tmp[sizeof(struct smb_hdr)+1] = 0;
354                                 return 0;
355                         }
356                         cifs_dbg(VFS, "rcvd invalid byte count (bcc)\n");
357                 } else {
358                         cifs_dbg(VFS, "Length less than smb header size\n");
359                 }
360                 return -EIO;
361         } else if (total_read < sizeof(*smb) + 2 * smb->WordCount) {
362                 cifs_dbg(VFS, "%s: can't read BCC due to invalid WordCount(%u)\n",
363                          __func__, smb->WordCount);
364                 return -EIO;
365         }
366
367         /* otherwise, there is enough to get to the BCC */
368         if (check_smb_hdr(smb))
369                 return -EIO;
370         clc_len = smbCalcSize(smb);
371
372         if (4 + rfclen != total_read) {
373                 cifs_dbg(VFS, "Length read does not match RFC1001 length %d\n",
374                          rfclen);
375                 return -EIO;
376         }
377
378         if (4 + rfclen != clc_len) {
379                 __u16 mid = get_mid(smb);
380                 /* check if bcc wrapped around for large read responses */
381                 if ((rfclen > 64 * 1024) && (rfclen > clc_len)) {
382                         /* check if lengths match mod 64K */
383                         if (((4 + rfclen) & 0xFFFF) == (clc_len & 0xFFFF))
384                                 return 0; /* bcc wrapped */
385                 }
386                 cifs_dbg(FYI, "Calculated size %u vs length %u mismatch for mid=%u\n",
387                          clc_len, 4 + rfclen, mid);
388
389                 if (4 + rfclen < clc_len) {
390                         cifs_dbg(VFS, "RFC1001 size %u smaller than SMB for mid=%u\n",
391                                  rfclen, mid);
392                         return -EIO;
393                 } else if (rfclen > clc_len + 512) {
394                         /*
395                          * Some servers (Windows XP in particular) send more
396                          * data than the lengths in the SMB packet would
397                          * indicate on certain calls (byte range locks and
398                          * trans2 find first calls in particular). While the
399                          * client can handle such a frame by ignoring the
400                          * trailing data, we choose limit the amount of extra
401                          * data to 512 bytes.
402                          */
403                         cifs_dbg(VFS, "RFC1001 size %u more than 512 bytes larger than SMB for mid=%u\n",
404                                  rfclen, mid);
405                         return -EIO;
406                 }
407         }
408         return 0;
409 }
410
411 bool
412 is_valid_oplock_break(char *buffer, struct TCP_Server_Info *srv)
413 {
414         struct smb_hdr *buf = (struct smb_hdr *)buffer;
415         struct smb_com_lock_req *pSMB = (struct smb_com_lock_req *)buf;
416         struct TCP_Server_Info *pserver;
417         struct cifs_ses *ses;
418         struct cifs_tcon *tcon;
419         struct cifsInodeInfo *pCifsInode;
420         struct cifsFileInfo *netfile;
421
422         cifs_dbg(FYI, "Checking for oplock break or dnotify response\n");
423         if ((pSMB->hdr.Command == SMB_COM_NT_TRANSACT) &&
424            (pSMB->hdr.Flags & SMBFLG_RESPONSE)) {
425                 struct smb_com_transaction_change_notify_rsp *pSMBr =
426                         (struct smb_com_transaction_change_notify_rsp *)buf;
427                 struct file_notify_information *pnotify;
428                 __u32 data_offset = 0;
429                 size_t len = srv->total_read - sizeof(pSMBr->hdr.smb_buf_length);
430
431                 if (get_bcc(buf) > sizeof(struct file_notify_information)) {
432                         data_offset = le32_to_cpu(pSMBr->DataOffset);
433
434                         if (data_offset >
435                             len - sizeof(struct file_notify_information)) {
436                                 cifs_dbg(FYI, "Invalid data_offset %u\n",
437                                          data_offset);
438                                 return true;
439                         }
440                         pnotify = (struct file_notify_information *)
441                                 ((char *)&pSMBr->hdr.Protocol + data_offset);
442                         cifs_dbg(FYI, "dnotify on %s Action: 0x%x\n",
443                                  pnotify->FileName, pnotify->Action);
444                         /*   cifs_dump_mem("Rcvd notify Data: ",buf,
445                                 sizeof(struct smb_hdr)+60); */
446                         return true;
447                 }
448                 if (pSMBr->hdr.Status.CifsError) {
449                         cifs_dbg(FYI, "notify err 0x%x\n",
450                                  pSMBr->hdr.Status.CifsError);
451                         return true;
452                 }
453                 return false;
454         }
455         if (pSMB->hdr.Command != SMB_COM_LOCKING_ANDX)
456                 return false;
457         if (pSMB->hdr.Flags & SMBFLG_RESPONSE) {
458                 /* no sense logging error on invalid handle on oplock
459                    break - harmless race between close request and oplock
460                    break response is expected from time to time writing out
461                    large dirty files cached on the client */
462                 if ((NT_STATUS_INVALID_HANDLE) ==
463                    le32_to_cpu(pSMB->hdr.Status.CifsError)) {
464                         cifs_dbg(FYI, "Invalid handle on oplock break\n");
465                         return true;
466                 } else if (ERRbadfid ==
467                    le16_to_cpu(pSMB->hdr.Status.DosError.Error)) {
468                         return true;
469                 } else {
470                         return false; /* on valid oplock brk we get "request" */
471                 }
472         }
473         if (pSMB->hdr.WordCount != 8)
474                 return false;
475
476         cifs_dbg(FYI, "oplock type 0x%x level 0x%x\n",
477                  pSMB->LockType, pSMB->OplockLevel);
478         if (!(pSMB->LockType & LOCKING_ANDX_OPLOCK_RELEASE))
479                 return false;
480
481         /* If server is a channel, select the primary channel */
482         pserver = SERVER_IS_CHAN(srv) ? srv->primary_server : srv;
483
484         /* look up tcon based on tid & uid */
485         spin_lock(&cifs_tcp_ses_lock);
486         list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
487                 if (cifs_ses_exiting(ses))
488                         continue;
489                 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
490                         if (tcon->tid != buf->Tid)
491                                 continue;
492
493                         cifs_stats_inc(&tcon->stats.cifs_stats.num_oplock_brks);
494                         spin_lock(&tcon->open_file_lock);
495                         list_for_each_entry(netfile, &tcon->openFileList, tlist) {
496                                 if (pSMB->Fid != netfile->fid.netfid)
497                                         continue;
498
499                                 cifs_dbg(FYI, "file id match, oplock break\n");
500                                 pCifsInode = CIFS_I(d_inode(netfile->dentry));
501
502                                 set_bit(CIFS_INODE_PENDING_OPLOCK_BREAK,
503                                         &pCifsInode->flags);
504
505                                 netfile->oplock_epoch = 0;
506                                 netfile->oplock_level = pSMB->OplockLevel;
507                                 netfile->oplock_break_cancelled = false;
508                                 cifs_queue_oplock_break(netfile);
509
510                                 spin_unlock(&tcon->open_file_lock);
511                                 spin_unlock(&cifs_tcp_ses_lock);
512                                 return true;
513                         }
514                         spin_unlock(&tcon->open_file_lock);
515                         spin_unlock(&cifs_tcp_ses_lock);
516                         cifs_dbg(FYI, "No matching file for oplock break\n");
517                         return true;
518                 }
519         }
520         spin_unlock(&cifs_tcp_ses_lock);
521         cifs_dbg(FYI, "Can not process oplock break for non-existent connection\n");
522         return true;
523 }
524
525 void
526 dump_smb(void *buf, int smb_buf_length)
527 {
528         if (traceSMB == 0)
529                 return;
530
531         print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_NONE, 8, 2, buf,
532                        smb_buf_length, true);
533 }
534
535 void
536 cifs_autodisable_serverino(struct cifs_sb_info *cifs_sb)
537 {
538         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) {
539                 struct cifs_tcon *tcon = NULL;
540
541                 if (cifs_sb->master_tlink)
542                         tcon = cifs_sb_master_tcon(cifs_sb);
543
544                 cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_SERVER_INUM;
545                 cifs_sb->mnt_cifs_serverino_autodisabled = true;
546                 cifs_dbg(VFS, "Autodisabling the use of server inode numbers on %s\n",
547                          tcon ? tcon->tree_name : "new server");
548                 cifs_dbg(VFS, "The server doesn't seem to support them properly or the files might be on different servers (DFS)\n");
549                 cifs_dbg(VFS, "Hardlinks will not be recognized on this mount. Consider mounting with the \"noserverino\" option to silence this message.\n");
550
551         }
552 }
553
554 void cifs_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock)
555 {
556         oplock &= 0xF;
557
558         if (oplock == OPLOCK_EXCLUSIVE) {
559                 cinode->oplock = CIFS_CACHE_WRITE_FLG | CIFS_CACHE_READ_FLG;
560                 cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
561                          &cinode->netfs.inode);
562         } else if (oplock == OPLOCK_READ) {
563                 cinode->oplock = CIFS_CACHE_READ_FLG;
564                 cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
565                          &cinode->netfs.inode);
566         } else
567                 cinode->oplock = 0;
568 }
569
570 /*
571  * We wait for oplock breaks to be processed before we attempt to perform
572  * writes.
573  */
574 int cifs_get_writer(struct cifsInodeInfo *cinode)
575 {
576         int rc;
577
578 start:
579         rc = wait_on_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK,
580                          TASK_KILLABLE);
581         if (rc)
582                 return rc;
583
584         spin_lock(&cinode->writers_lock);
585         if (!cinode->writers)
586                 set_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
587         cinode->writers++;
588         /* Check to see if we have started servicing an oplock break */
589         if (test_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags)) {
590                 cinode->writers--;
591                 if (cinode->writers == 0) {
592                         clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
593                         wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
594                 }
595                 spin_unlock(&cinode->writers_lock);
596                 goto start;
597         }
598         spin_unlock(&cinode->writers_lock);
599         return 0;
600 }
601
602 void cifs_put_writer(struct cifsInodeInfo *cinode)
603 {
604         spin_lock(&cinode->writers_lock);
605         cinode->writers--;
606         if (cinode->writers == 0) {
607                 clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
608                 wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
609         }
610         spin_unlock(&cinode->writers_lock);
611 }
612
613 /**
614  * cifs_queue_oplock_break - queue the oplock break handler for cfile
615  * @cfile: The file to break the oplock on
616  *
617  * This function is called from the demultiplex thread when it
618  * receives an oplock break for @cfile.
619  *
620  * Assumes the tcon->open_file_lock is held.
621  * Assumes cfile->file_info_lock is NOT held.
622  */
623 void cifs_queue_oplock_break(struct cifsFileInfo *cfile)
624 {
625         /*
626          * Bump the handle refcount now while we hold the
627          * open_file_lock to enforce the validity of it for the oplock
628          * break handler. The matching put is done at the end of the
629          * handler.
630          */
631         cifsFileInfo_get(cfile);
632
633         queue_work(cifsoplockd_wq, &cfile->oplock_break);
634 }
635
636 void cifs_done_oplock_break(struct cifsInodeInfo *cinode)
637 {
638         clear_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags);
639         wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK);
640 }
641
642 bool
643 backup_cred(struct cifs_sb_info *cifs_sb)
644 {
645         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPUID) {
646                 if (uid_eq(cifs_sb->ctx->backupuid, current_fsuid()))
647                         return true;
648         }
649         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPGID) {
650                 if (in_group_p(cifs_sb->ctx->backupgid))
651                         return true;
652         }
653
654         return false;
655 }
656
657 void
658 cifs_del_pending_open(struct cifs_pending_open *open)
659 {
660         spin_lock(&tlink_tcon(open->tlink)->open_file_lock);
661         list_del(&open->olist);
662         spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
663 }
664
665 void
666 cifs_add_pending_open_locked(struct cifs_fid *fid, struct tcon_link *tlink,
667                              struct cifs_pending_open *open)
668 {
669         memcpy(open->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
670         open->oplock = CIFS_OPLOCK_NO_CHANGE;
671         open->tlink = tlink;
672         fid->pending_open = open;
673         list_add_tail(&open->olist, &tlink_tcon(tlink)->pending_opens);
674 }
675
676 void
677 cifs_add_pending_open(struct cifs_fid *fid, struct tcon_link *tlink,
678                       struct cifs_pending_open *open)
679 {
680         spin_lock(&tlink_tcon(tlink)->open_file_lock);
681         cifs_add_pending_open_locked(fid, tlink, open);
682         spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
683 }
684
685 /*
686  * Critical section which runs after acquiring deferred_lock.
687  * As there is no reference count on cifs_deferred_close, pdclose
688  * should not be used outside deferred_lock.
689  */
690 bool
691 cifs_is_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close **pdclose)
692 {
693         struct cifs_deferred_close *dclose;
694
695         list_for_each_entry(dclose, &CIFS_I(d_inode(cfile->dentry))->deferred_closes, dlist) {
696                 if ((dclose->netfid == cfile->fid.netfid) &&
697                         (dclose->persistent_fid == cfile->fid.persistent_fid) &&
698                         (dclose->volatile_fid == cfile->fid.volatile_fid)) {
699                         *pdclose = dclose;
700                         return true;
701                 }
702         }
703         return false;
704 }
705
706 /*
707  * Critical section which runs after acquiring deferred_lock.
708  */
709 void
710 cifs_add_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close *dclose)
711 {
712         bool is_deferred = false;
713         struct cifs_deferred_close *pdclose;
714
715         is_deferred = cifs_is_deferred_close(cfile, &pdclose);
716         if (is_deferred) {
717                 kfree(dclose);
718                 return;
719         }
720
721         dclose->tlink = cfile->tlink;
722         dclose->netfid = cfile->fid.netfid;
723         dclose->persistent_fid = cfile->fid.persistent_fid;
724         dclose->volatile_fid = cfile->fid.volatile_fid;
725         list_add_tail(&dclose->dlist, &CIFS_I(d_inode(cfile->dentry))->deferred_closes);
726 }
727
728 /*
729  * Critical section which runs after acquiring deferred_lock.
730  */
731 void
732 cifs_del_deferred_close(struct cifsFileInfo *cfile)
733 {
734         bool is_deferred = false;
735         struct cifs_deferred_close *dclose;
736
737         is_deferred = cifs_is_deferred_close(cfile, &dclose);
738         if (!is_deferred)
739                 return;
740         list_del(&dclose->dlist);
741         kfree(dclose);
742 }
743
744 void
745 cifs_close_deferred_file(struct cifsInodeInfo *cifs_inode)
746 {
747         struct cifsFileInfo *cfile = NULL;
748         struct file_list *tmp_list, *tmp_next_list;
749         struct list_head file_head;
750
751         if (cifs_inode == NULL)
752                 return;
753
754         INIT_LIST_HEAD(&file_head);
755         spin_lock(&cifs_inode->open_file_lock);
756         list_for_each_entry(cfile, &cifs_inode->openFileList, flist) {
757                 if (delayed_work_pending(&cfile->deferred)) {
758                         if (cancel_delayed_work(&cfile->deferred)) {
759                                 spin_lock(&cifs_inode->deferred_lock);
760                                 cifs_del_deferred_close(cfile);
761                                 spin_unlock(&cifs_inode->deferred_lock);
762
763                                 tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
764                                 if (tmp_list == NULL)
765                                         break;
766                                 tmp_list->cfile = cfile;
767                                 list_add_tail(&tmp_list->list, &file_head);
768                         }
769                 }
770         }
771         spin_unlock(&cifs_inode->open_file_lock);
772
773         list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
774                 _cifsFileInfo_put(tmp_list->cfile, false, false);
775                 list_del(&tmp_list->list);
776                 kfree(tmp_list);
777         }
778 }
779
780 void
781 cifs_close_all_deferred_files(struct cifs_tcon *tcon)
782 {
783         struct cifsFileInfo *cfile;
784         struct file_list *tmp_list, *tmp_next_list;
785         struct list_head file_head;
786
787         INIT_LIST_HEAD(&file_head);
788         spin_lock(&tcon->open_file_lock);
789         list_for_each_entry(cfile, &tcon->openFileList, tlist) {
790                 if (delayed_work_pending(&cfile->deferred)) {
791                         if (cancel_delayed_work(&cfile->deferred)) {
792                                 spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
793                                 cifs_del_deferred_close(cfile);
794                                 spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
795
796                                 tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
797                                 if (tmp_list == NULL)
798                                         break;
799                                 tmp_list->cfile = cfile;
800                                 list_add_tail(&tmp_list->list, &file_head);
801                         }
802                 }
803         }
804         spin_unlock(&tcon->open_file_lock);
805
806         list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
807                 _cifsFileInfo_put(tmp_list->cfile, true, false);
808                 list_del(&tmp_list->list);
809                 kfree(tmp_list);
810         }
811 }
812 void
813 cifs_close_deferred_file_under_dentry(struct cifs_tcon *tcon, const char *path)
814 {
815         struct cifsFileInfo *cfile;
816         struct file_list *tmp_list, *tmp_next_list;
817         struct list_head file_head;
818         void *page;
819         const char *full_path;
820
821         INIT_LIST_HEAD(&file_head);
822         page = alloc_dentry_path();
823         spin_lock(&tcon->open_file_lock);
824         list_for_each_entry(cfile, &tcon->openFileList, tlist) {
825                 full_path = build_path_from_dentry(cfile->dentry, page);
826                 if (strstr(full_path, path)) {
827                         if (delayed_work_pending(&cfile->deferred)) {
828                                 if (cancel_delayed_work(&cfile->deferred)) {
829                                         spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
830                                         cifs_del_deferred_close(cfile);
831                                         spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
832
833                                         tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
834                                         if (tmp_list == NULL)
835                                                 break;
836                                         tmp_list->cfile = cfile;
837                                         list_add_tail(&tmp_list->list, &file_head);
838                                 }
839                         }
840                 }
841         }
842         spin_unlock(&tcon->open_file_lock);
843
844         list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
845                 _cifsFileInfo_put(tmp_list->cfile, true, false);
846                 list_del(&tmp_list->list);
847                 kfree(tmp_list);
848         }
849         free_dentry_path(page);
850 }
851
852 /* parses DFS referral V3 structure
853  * caller is responsible for freeing target_nodes
854  * returns:
855  * - on success - 0
856  * - on failure - errno
857  */
858 int
859 parse_dfs_referrals(struct get_dfs_referral_rsp *rsp, u32 rsp_size,
860                     unsigned int *num_of_nodes,
861                     struct dfs_info3_param **target_nodes,
862                     const struct nls_table *nls_codepage, int remap,
863                     const char *searchName, bool is_unicode)
864 {
865         int i, rc = 0;
866         char *data_end;
867         struct dfs_referral_level_3 *ref;
868
869         *num_of_nodes = le16_to_cpu(rsp->NumberOfReferrals);
870
871         if (*num_of_nodes < 1) {
872                 cifs_dbg(VFS, "num_referrals: must be at least > 0, but we get num_referrals = %d\n",
873                          *num_of_nodes);
874                 rc = -EINVAL;
875                 goto parse_DFS_referrals_exit;
876         }
877
878         ref = (struct dfs_referral_level_3 *) &(rsp->referrals);
879         if (ref->VersionNumber != cpu_to_le16(3)) {
880                 cifs_dbg(VFS, "Referrals of V%d version are not supported, should be V3\n",
881                          le16_to_cpu(ref->VersionNumber));
882                 rc = -EINVAL;
883                 goto parse_DFS_referrals_exit;
884         }
885
886         /* get the upper boundary of the resp buffer */
887         data_end = (char *)rsp + rsp_size;
888
889         cifs_dbg(FYI, "num_referrals: %d dfs flags: 0x%x ...\n",
890                  *num_of_nodes, le32_to_cpu(rsp->DFSFlags));
891
892         *target_nodes = kcalloc(*num_of_nodes, sizeof(struct dfs_info3_param),
893                                 GFP_KERNEL);
894         if (*target_nodes == NULL) {
895                 rc = -ENOMEM;
896                 goto parse_DFS_referrals_exit;
897         }
898
899         /* collect necessary data from referrals */
900         for (i = 0; i < *num_of_nodes; i++) {
901                 char *temp;
902                 int max_len;
903                 struct dfs_info3_param *node = (*target_nodes)+i;
904
905                 node->flags = le32_to_cpu(rsp->DFSFlags);
906                 if (is_unicode) {
907                         __le16 *tmp = kmalloc(strlen(searchName)*2 + 2,
908                                                 GFP_KERNEL);
909                         if (tmp == NULL) {
910                                 rc = -ENOMEM;
911                                 goto parse_DFS_referrals_exit;
912                         }
913                         cifsConvertToUTF16((__le16 *) tmp, searchName,
914                                            PATH_MAX, nls_codepage, remap);
915                         node->path_consumed = cifs_utf16_bytes(tmp,
916                                         le16_to_cpu(rsp->PathConsumed),
917                                         nls_codepage);
918                         kfree(tmp);
919                 } else
920                         node->path_consumed = le16_to_cpu(rsp->PathConsumed);
921
922                 node->server_type = le16_to_cpu(ref->ServerType);
923                 node->ref_flag = le16_to_cpu(ref->ReferralEntryFlags);
924
925                 /* copy DfsPath */
926                 temp = (char *)ref + le16_to_cpu(ref->DfsPathOffset);
927                 max_len = data_end - temp;
928                 node->path_name = cifs_strndup_from_utf16(temp, max_len,
929                                                 is_unicode, nls_codepage);
930                 if (!node->path_name) {
931                         rc = -ENOMEM;
932                         goto parse_DFS_referrals_exit;
933                 }
934
935                 /* copy link target UNC */
936                 temp = (char *)ref + le16_to_cpu(ref->NetworkAddressOffset);
937                 max_len = data_end - temp;
938                 node->node_name = cifs_strndup_from_utf16(temp, max_len,
939                                                 is_unicode, nls_codepage);
940                 if (!node->node_name) {
941                         rc = -ENOMEM;
942                         goto parse_DFS_referrals_exit;
943                 }
944
945                 node->ttl = le32_to_cpu(ref->TimeToLive);
946
947                 ref++;
948         }
949
950 parse_DFS_referrals_exit:
951         if (rc) {
952                 free_dfs_info_array(*target_nodes, *num_of_nodes);
953                 *target_nodes = NULL;
954                 *num_of_nodes = 0;
955         }
956         return rc;
957 }
958
959 struct cifs_aio_ctx *
960 cifs_aio_ctx_alloc(void)
961 {
962         struct cifs_aio_ctx *ctx;
963
964         /*
965          * Must use kzalloc to initialize ctx->bv to NULL and ctx->direct_io
966          * to false so that we know when we have to unreference pages within
967          * cifs_aio_ctx_release()
968          */
969         ctx = kzalloc(sizeof(struct cifs_aio_ctx), GFP_KERNEL);
970         if (!ctx)
971                 return NULL;
972
973         INIT_LIST_HEAD(&ctx->list);
974         mutex_init(&ctx->aio_mutex);
975         init_completion(&ctx->done);
976         kref_init(&ctx->refcount);
977         return ctx;
978 }
979
980 void
981 cifs_aio_ctx_release(struct kref *refcount)
982 {
983         struct cifs_aio_ctx *ctx = container_of(refcount,
984                                         struct cifs_aio_ctx, refcount);
985
986         cifsFileInfo_put(ctx->cfile);
987
988         /*
989          * ctx->bv is only set if setup_aio_ctx_iter() was call successfuly
990          * which means that iov_iter_extract_pages() was a success and thus
991          * that we may have references or pins on pages that we need to
992          * release.
993          */
994         if (ctx->bv) {
995                 if (ctx->should_dirty || ctx->bv_need_unpin) {
996                         unsigned int i;
997
998                         for (i = 0; i < ctx->nr_pinned_pages; i++) {
999                                 struct page *page = ctx->bv[i].bv_page;
1000
1001                                 if (ctx->should_dirty)
1002                                         set_page_dirty(page);
1003                                 if (ctx->bv_need_unpin)
1004                                         unpin_user_page(page);
1005                         }
1006                 }
1007                 kvfree(ctx->bv);
1008         }
1009
1010         kfree(ctx);
1011 }
1012
1013 /**
1014  * cifs_alloc_hash - allocate hash and hash context together
1015  * @name: The name of the crypto hash algo
1016  * @sdesc: SHASH descriptor where to put the pointer to the hash TFM
1017  *
1018  * The caller has to make sure @sdesc is initialized to either NULL or
1019  * a valid context. It can be freed via cifs_free_hash().
1020  */
1021 int
1022 cifs_alloc_hash(const char *name, struct shash_desc **sdesc)
1023 {
1024         int rc = 0;
1025         struct crypto_shash *alg = NULL;
1026
1027         if (*sdesc)
1028                 return 0;
1029
1030         alg = crypto_alloc_shash(name, 0, 0);
1031         if (IS_ERR(alg)) {
1032                 cifs_dbg(VFS, "Could not allocate shash TFM '%s'\n", name);
1033                 rc = PTR_ERR(alg);
1034                 *sdesc = NULL;
1035                 return rc;
1036         }
1037
1038         *sdesc = kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(alg), GFP_KERNEL);
1039         if (*sdesc == NULL) {
1040                 cifs_dbg(VFS, "no memory left to allocate shash TFM '%s'\n", name);
1041                 crypto_free_shash(alg);
1042                 return -ENOMEM;
1043         }
1044
1045         (*sdesc)->tfm = alg;
1046         return 0;
1047 }
1048
1049 /**
1050  * cifs_free_hash - free hash and hash context together
1051  * @sdesc: Where to find the pointer to the hash TFM
1052  *
1053  * Freeing a NULL descriptor is safe.
1054  */
1055 void
1056 cifs_free_hash(struct shash_desc **sdesc)
1057 {
1058         if (unlikely(!sdesc) || !*sdesc)
1059                 return;
1060
1061         if ((*sdesc)->tfm) {
1062                 crypto_free_shash((*sdesc)->tfm);
1063                 (*sdesc)->tfm = NULL;
1064         }
1065
1066         kfree_sensitive(*sdesc);
1067         *sdesc = NULL;
1068 }
1069
1070 void extract_unc_hostname(const char *unc, const char **h, size_t *len)
1071 {
1072         const char *end;
1073
1074         /* skip initial slashes */
1075         while (*unc && (*unc == '\\' || *unc == '/'))
1076                 unc++;
1077
1078         end = unc;
1079
1080         while (*end && !(*end == '\\' || *end == '/'))
1081                 end++;
1082
1083         *h = unc;
1084         *len = end - unc;
1085 }
1086
1087 /**
1088  * copy_path_name - copy src path to dst, possibly truncating
1089  * @dst: The destination buffer
1090  * @src: The source name
1091  *
1092  * returns number of bytes written (including trailing nul)
1093  */
1094 int copy_path_name(char *dst, const char *src)
1095 {
1096         int name_len;
1097
1098         /*
1099          * PATH_MAX includes nul, so if strlen(src) >= PATH_MAX it
1100          * will truncate and strlen(dst) will be PATH_MAX-1
1101          */
1102         name_len = strscpy(dst, src, PATH_MAX);
1103         if (WARN_ON_ONCE(name_len < 0))
1104                 name_len = PATH_MAX-1;
1105
1106         /* we count the trailing nul */
1107         name_len++;
1108         return name_len;
1109 }
1110
1111 struct super_cb_data {
1112         void *data;
1113         struct super_block *sb;
1114 };
1115
1116 static void tcon_super_cb(struct super_block *sb, void *arg)
1117 {
1118         struct super_cb_data *sd = arg;
1119         struct cifs_sb_info *cifs_sb;
1120         struct cifs_tcon *t1 = sd->data, *t2;
1121
1122         if (sd->sb)
1123                 return;
1124
1125         cifs_sb = CIFS_SB(sb);
1126         t2 = cifs_sb_master_tcon(cifs_sb);
1127
1128         spin_lock(&t2->tc_lock);
1129         if (t1->ses == t2->ses &&
1130             t1->ses->server == t2->ses->server &&
1131             t2->origin_fullpath &&
1132             dfs_src_pathname_equal(t2->origin_fullpath, t1->origin_fullpath))
1133                 sd->sb = sb;
1134         spin_unlock(&t2->tc_lock);
1135 }
1136
1137 static struct super_block *__cifs_get_super(void (*f)(struct super_block *, void *),
1138                                             void *data)
1139 {
1140         struct super_cb_data sd = {
1141                 .data = data,
1142                 .sb = NULL,
1143         };
1144         struct file_system_type **fs_type = (struct file_system_type *[]) {
1145                 &cifs_fs_type, &smb3_fs_type, NULL,
1146         };
1147
1148         for (; *fs_type; fs_type++) {
1149                 iterate_supers_type(*fs_type, f, &sd);
1150                 if (sd.sb) {
1151                         /*
1152                          * Grab an active reference in order to prevent automounts (DFS links)
1153                          * of expiring and then freeing up our cifs superblock pointer while
1154                          * we're doing failover.
1155                          */
1156                         cifs_sb_active(sd.sb);
1157                         return sd.sb;
1158                 }
1159         }
1160         pr_warn_once("%s: could not find dfs superblock\n", __func__);
1161         return ERR_PTR(-EINVAL);
1162 }
1163
1164 static void __cifs_put_super(struct super_block *sb)
1165 {
1166         if (!IS_ERR_OR_NULL(sb))
1167                 cifs_sb_deactive(sb);
1168 }
1169
1170 struct super_block *cifs_get_dfs_tcon_super(struct cifs_tcon *tcon)
1171 {
1172         spin_lock(&tcon->tc_lock);
1173         if (!tcon->origin_fullpath) {
1174                 spin_unlock(&tcon->tc_lock);
1175                 return ERR_PTR(-ENOENT);
1176         }
1177         spin_unlock(&tcon->tc_lock);
1178         return __cifs_get_super(tcon_super_cb, tcon);
1179 }
1180
1181 void cifs_put_tcp_super(struct super_block *sb)
1182 {
1183         __cifs_put_super(sb);
1184 }
1185
1186 #ifdef CONFIG_CIFS_DFS_UPCALL
1187 int match_target_ip(struct TCP_Server_Info *server,
1188                     const char *share, size_t share_len,
1189                     bool *result)
1190 {
1191         int rc;
1192         char *target;
1193         struct sockaddr_storage ss;
1194
1195         *result = false;
1196
1197         target = kzalloc(share_len + 3, GFP_KERNEL);
1198         if (!target)
1199                 return -ENOMEM;
1200
1201         scnprintf(target, share_len + 3, "\\\\%.*s", (int)share_len, share);
1202
1203         cifs_dbg(FYI, "%s: target name: %s\n", __func__, target + 2);
1204
1205         rc = dns_resolve_server_name_to_ip(target, (struct sockaddr *)&ss, NULL);
1206         kfree(target);
1207
1208         if (rc < 0)
1209                 return rc;
1210
1211         spin_lock(&server->srv_lock);
1212         *result = cifs_match_ipaddr((struct sockaddr *)&server->dstaddr, (struct sockaddr *)&ss);
1213         spin_unlock(&server->srv_lock);
1214         cifs_dbg(FYI, "%s: ip addresses match: %u\n", __func__, *result);
1215         return 0;
1216 }
1217
1218 int cifs_update_super_prepath(struct cifs_sb_info *cifs_sb, char *prefix)
1219 {
1220         int rc;
1221
1222         kfree(cifs_sb->prepath);
1223         cifs_sb->prepath = NULL;
1224
1225         if (prefix && *prefix) {
1226                 cifs_sb->prepath = cifs_sanitize_prepath(prefix, GFP_ATOMIC);
1227                 if (IS_ERR(cifs_sb->prepath)) {
1228                         rc = PTR_ERR(cifs_sb->prepath);
1229                         cifs_sb->prepath = NULL;
1230                         return rc;
1231                 }
1232                 if (cifs_sb->prepath)
1233                         convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb));
1234         }
1235
1236         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
1237         return 0;
1238 }
1239
1240 /*
1241  * Handle weird Windows SMB server behaviour. It responds with
1242  * STATUS_OBJECT_NAME_INVALID code to SMB2 QUERY_INFO request for
1243  * "\<server>\<dfsname>\<linkpath>" DFS reference, where <dfsname> contains
1244  * non-ASCII unicode symbols.
1245  */
1246 int cifs_inval_name_dfs_link_error(const unsigned int xid,
1247                                    struct cifs_tcon *tcon,
1248                                    struct cifs_sb_info *cifs_sb,
1249                                    const char *full_path,
1250                                    bool *islink)
1251 {
1252         struct cifs_ses *ses = tcon->ses;
1253         size_t len;
1254         char *path;
1255         char *ref_path;
1256
1257         *islink = false;
1258
1259         /*
1260          * Fast path - skip check when @full_path doesn't have a prefix path to
1261          * look up or tcon is not DFS.
1262          */
1263         if (strlen(full_path) < 2 || !cifs_sb ||
1264             (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
1265             !is_tcon_dfs(tcon))
1266                 return 0;
1267
1268         spin_lock(&tcon->tc_lock);
1269         if (!tcon->origin_fullpath) {
1270                 spin_unlock(&tcon->tc_lock);
1271                 return 0;
1272         }
1273         spin_unlock(&tcon->tc_lock);
1274
1275         /*
1276          * Slow path - tcon is DFS and @full_path has prefix path, so attempt
1277          * to get a referral to figure out whether it is an DFS link.
1278          */
1279         len = strnlen(tcon->tree_name, MAX_TREE_SIZE + 1) + strlen(full_path) + 1;
1280         path = kmalloc(len, GFP_KERNEL);
1281         if (!path)
1282                 return -ENOMEM;
1283
1284         scnprintf(path, len, "%s%s", tcon->tree_name, full_path);
1285         ref_path = dfs_cache_canonical_path(path + 1, cifs_sb->local_nls,
1286                                             cifs_remap(cifs_sb));
1287         kfree(path);
1288
1289         if (IS_ERR(ref_path)) {
1290                 if (PTR_ERR(ref_path) != -EINVAL)
1291                         return PTR_ERR(ref_path);
1292         } else {
1293                 struct dfs_info3_param *refs = NULL;
1294                 int num_refs = 0;
1295
1296                 /*
1297                  * XXX: we are not using dfs_cache_find() here because we might
1298                  * end up filling all the DFS cache and thus potentially
1299                  * removing cached DFS targets that the client would eventually
1300                  * need during failover.
1301                  */
1302                 ses = CIFS_DFS_ROOT_SES(ses);
1303                 if (ses->server->ops->get_dfs_refer &&
1304                     !ses->server->ops->get_dfs_refer(xid, ses, ref_path, &refs,
1305                                                      &num_refs, cifs_sb->local_nls,
1306                                                      cifs_remap(cifs_sb)))
1307                         *islink = refs[0].server_type == DFS_TYPE_LINK;
1308                 free_dfs_info_array(refs, num_refs);
1309                 kfree(ref_path);
1310         }
1311         return 0;
1312 }
1313 #endif
1314
1315 int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry)
1316 {
1317         int timeout = 10;
1318         int rc;
1319
1320         spin_lock(&server->srv_lock);
1321         if (server->tcpStatus != CifsNeedReconnect) {
1322                 spin_unlock(&server->srv_lock);
1323                 return 0;
1324         }
1325         timeout *= server->nr_targets;
1326         spin_unlock(&server->srv_lock);
1327
1328         /*
1329          * Give demultiplex thread up to 10 seconds to each target available for
1330          * reconnect -- should be greater than cifs socket timeout which is 7
1331          * seconds.
1332          *
1333          * On "soft" mounts we wait once. Hard mounts keep retrying until
1334          * process is killed or server comes back on-line.
1335          */
1336         do {
1337                 rc = wait_event_interruptible_timeout(server->response_q,
1338                                                       (server->tcpStatus != CifsNeedReconnect),
1339                                                       timeout * HZ);
1340                 if (rc < 0) {
1341                         cifs_dbg(FYI, "%s: aborting reconnect due to received signal\n",
1342                                  __func__);
1343                         return -ERESTARTSYS;
1344                 }
1345
1346                 /* are we still trying to reconnect? */
1347                 spin_lock(&server->srv_lock);
1348                 if (server->tcpStatus != CifsNeedReconnect) {
1349                         spin_unlock(&server->srv_lock);
1350                         return 0;
1351                 }
1352                 spin_unlock(&server->srv_lock);
1353         } while (retry);
1354
1355         cifs_dbg(FYI, "%s: gave up waiting on reconnect\n", __func__);
1356         return -EHOSTDOWN;
1357 }