1 // SPDX-License-Identifier: LGPL-2.1
4 * Copyright (C) International Business Machines Corp., 2002,2008
5 * Author(s): Steve French (sfrench@us.ibm.com)
9 #include <linux/slab.h>
10 #include <linux/ctype.h>
11 #include <linux/mempool.h>
12 #include <linux/vmalloc.h>
15 #include "cifsproto.h"
16 #include "cifs_debug.h"
19 #include "cifs_unicode.h"
22 #ifdef CONFIG_CIFS_DFS_UPCALL
23 #include "dns_resolve.h"
24 #include "dfs_cache.h"
27 #include "fs_context.h"
28 #include "cached_dir.h"
30 /* The xid serves as a useful identifier for each incoming vfs request,
31 in a similar way to the mid which is useful to track each sent smb,
32 and CurrentXid can also provide a running counter (although it
33 will eventually wrap past zero) of the total vfs operations handled
34 since the cifs fs was mounted */
41 spin_lock(&GlobalMid_Lock);
42 GlobalTotalActiveXid++;
44 /* keep high water mark for number of simultaneous ops in filesystem */
45 if (GlobalTotalActiveXid > GlobalMaxActiveXid)
46 GlobalMaxActiveXid = GlobalTotalActiveXid;
47 if (GlobalTotalActiveXid > 65000)
48 cifs_dbg(FYI, "warning: more than 65000 requests active\n");
49 xid = GlobalCurrentXid++;
50 spin_unlock(&GlobalMid_Lock);
55 _free_xid(unsigned int xid)
57 spin_lock(&GlobalMid_Lock);
58 /* if (GlobalTotalActiveXid == 0)
60 GlobalTotalActiveXid--;
61 spin_unlock(&GlobalMid_Lock);
67 struct cifs_ses *ret_buf;
69 ret_buf = kzalloc(sizeof(struct cifs_ses), GFP_KERNEL);
71 atomic_inc(&sesInfoAllocCount);
72 spin_lock_init(&ret_buf->ses_lock);
73 ret_buf->ses_status = SES_NEW;
75 INIT_LIST_HEAD(&ret_buf->smb_ses_list);
76 INIT_LIST_HEAD(&ret_buf->tcon_list);
77 mutex_init(&ret_buf->session_mutex);
78 spin_lock_init(&ret_buf->iface_lock);
79 INIT_LIST_HEAD(&ret_buf->iface_list);
80 spin_lock_init(&ret_buf->chan_lock);
86 sesInfoFree(struct cifs_ses *buf_to_free)
88 struct cifs_server_iface *iface = NULL, *niface = NULL;
90 if (buf_to_free == NULL) {
91 cifs_dbg(FYI, "Null buffer passed to sesInfoFree\n");
95 unload_nls(buf_to_free->local_nls);
96 atomic_dec(&sesInfoAllocCount);
97 kfree(buf_to_free->serverOS);
98 kfree(buf_to_free->serverDomain);
99 kfree(buf_to_free->serverNOS);
100 kfree_sensitive(buf_to_free->password);
101 kfree(buf_to_free->user_name);
102 kfree(buf_to_free->domainName);
103 kfree_sensitive(buf_to_free->auth_key.response);
104 spin_lock(&buf_to_free->iface_lock);
105 list_for_each_entry_safe(iface, niface, &buf_to_free->iface_list,
107 kref_put(&iface->refcount, release_iface);
108 spin_unlock(&buf_to_free->iface_lock);
109 kfree_sensitive(buf_to_free);
113 tcon_info_alloc(bool dir_leases_enabled)
115 struct cifs_tcon *ret_buf;
117 ret_buf = kzalloc(sizeof(*ret_buf), GFP_KERNEL);
121 if (dir_leases_enabled == true) {
122 ret_buf->cfids = init_cached_dirs();
123 if (!ret_buf->cfids) {
128 /* else ret_buf->cfids is already set to NULL above */
130 atomic_inc(&tconInfoAllocCount);
131 ret_buf->status = TID_NEW;
133 spin_lock_init(&ret_buf->tc_lock);
134 INIT_LIST_HEAD(&ret_buf->openFileList);
135 INIT_LIST_HEAD(&ret_buf->tcon_list);
136 spin_lock_init(&ret_buf->open_file_lock);
137 spin_lock_init(&ret_buf->stat_lock);
138 atomic_set(&ret_buf->num_local_opens, 0);
139 atomic_set(&ret_buf->num_remote_opens, 0);
140 ret_buf->stats_from_time = ktime_get_real_seconds();
141 #ifdef CONFIG_CIFS_DFS_UPCALL
142 INIT_LIST_HEAD(&ret_buf->dfs_ses_list);
149 tconInfoFree(struct cifs_tcon *tcon)
152 cifs_dbg(FYI, "Null buffer passed to tconInfoFree\n");
155 free_cached_dirs(tcon->cfids);
156 atomic_dec(&tconInfoAllocCount);
157 kfree(tcon->nativeFileSystem);
158 kfree_sensitive(tcon->password);
159 #ifdef CONFIG_CIFS_DFS_UPCALL
160 dfs_put_root_smb_sessions(&tcon->dfs_ses_list);
162 kfree(tcon->origin_fullpath);
169 struct smb_hdr *ret_buf = NULL;
171 * SMB2 header is bigger than CIFS one - no problems to clean some
172 * more bytes for CIFS.
174 size_t buf_size = sizeof(struct smb2_hdr);
177 * We could use negotiated size instead of max_msgsize -
178 * but it may be more efficient to always alloc same size
179 * albeit slightly larger than necessary and maxbuffersize
180 * defaults to this and can not be bigger.
182 ret_buf = mempool_alloc(cifs_req_poolp, GFP_NOFS);
184 /* clear the first few header bytes */
185 /* for most paths, more is cleared in header_assemble */
186 memset(ret_buf, 0, buf_size + 3);
187 atomic_inc(&buf_alloc_count);
188 #ifdef CONFIG_CIFS_STATS2
189 atomic_inc(&total_buf_alloc_count);
190 #endif /* CONFIG_CIFS_STATS2 */
196 cifs_buf_release(void *buf_to_free)
198 if (buf_to_free == NULL) {
199 /* cifs_dbg(FYI, "Null buffer passed to cifs_buf_release\n");*/
202 mempool_free(buf_to_free, cifs_req_poolp);
204 atomic_dec(&buf_alloc_count);
209 cifs_small_buf_get(void)
211 struct smb_hdr *ret_buf = NULL;
213 /* We could use negotiated size instead of max_msgsize -
214 but it may be more efficient to always alloc same size
215 albeit slightly larger than necessary and maxbuffersize
216 defaults to this and can not be bigger */
217 ret_buf = mempool_alloc(cifs_sm_req_poolp, GFP_NOFS);
218 /* No need to clear memory here, cleared in header assemble */
219 /* memset(ret_buf, 0, sizeof(struct smb_hdr) + 27);*/
220 atomic_inc(&small_buf_alloc_count);
221 #ifdef CONFIG_CIFS_STATS2
222 atomic_inc(&total_small_buf_alloc_count);
223 #endif /* CONFIG_CIFS_STATS2 */
229 cifs_small_buf_release(void *buf_to_free)
232 if (buf_to_free == NULL) {
233 cifs_dbg(FYI, "Null buffer passed to cifs_small_buf_release\n");
236 mempool_free(buf_to_free, cifs_sm_req_poolp);
238 atomic_dec(&small_buf_alloc_count);
243 free_rsp_buf(int resp_buftype, void *rsp)
245 if (resp_buftype == CIFS_SMALL_BUFFER)
246 cifs_small_buf_release(rsp);
247 else if (resp_buftype == CIFS_LARGE_BUFFER)
248 cifs_buf_release(rsp);
251 /* NB: MID can not be set if treeCon not passed in, in that
252 case it is responsbility of caller to set the mid */
254 header_assemble(struct smb_hdr *buffer, char smb_command /* command */ ,
255 const struct cifs_tcon *treeCon, int word_count
256 /* length of fixed section (word count) in two byte units */)
258 char *temp = (char *) buffer;
260 memset(temp, 0, 256); /* bigger than MAX_CIFS_HDR_SIZE */
262 buffer->smb_buf_length = cpu_to_be32(
263 (2 * word_count) + sizeof(struct smb_hdr) -
264 4 /* RFC 1001 length field does not count */ +
265 2 /* for bcc field itself */) ;
267 buffer->Protocol[0] = 0xFF;
268 buffer->Protocol[1] = 'S';
269 buffer->Protocol[2] = 'M';
270 buffer->Protocol[3] = 'B';
271 buffer->Command = smb_command;
272 buffer->Flags = 0x00; /* case sensitive */
273 buffer->Flags2 = SMBFLG2_KNOWS_LONG_NAMES;
274 buffer->Pid = cpu_to_le16((__u16)current->tgid);
275 buffer->PidHigh = cpu_to_le16((__u16)(current->tgid >> 16));
277 buffer->Tid = treeCon->tid;
279 if (treeCon->ses->capabilities & CAP_UNICODE)
280 buffer->Flags2 |= SMBFLG2_UNICODE;
281 if (treeCon->ses->capabilities & CAP_STATUS32)
282 buffer->Flags2 |= SMBFLG2_ERR_STATUS;
284 /* Uid is not converted */
285 buffer->Uid = treeCon->ses->Suid;
286 if (treeCon->ses->server)
287 buffer->Mid = get_next_mid(treeCon->ses->server);
289 if (treeCon->Flags & SMB_SHARE_IS_IN_DFS)
290 buffer->Flags2 |= SMBFLG2_DFS;
292 buffer->Flags |= SMBFLG_CASELESS;
293 if ((treeCon->ses) && (treeCon->ses->server))
294 if (treeCon->ses->server->sign)
295 buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
298 /* endian conversion of flags is now done just before sending */
299 buffer->WordCount = (char) word_count;
304 check_smb_hdr(struct smb_hdr *smb)
306 /* does it have the right SMB "signature" ? */
307 if (*(__le32 *) smb->Protocol != cpu_to_le32(0x424d53ff)) {
308 cifs_dbg(VFS, "Bad protocol string signature header 0x%x\n",
309 *(unsigned int *)smb->Protocol);
313 /* if it's a response then accept */
314 if (smb->Flags & SMBFLG_RESPONSE)
317 /* only one valid case where server sends us request */
318 if (smb->Command == SMB_COM_LOCKING_ANDX)
321 cifs_dbg(VFS, "Server sent request, not response. mid=%u\n",
327 checkSMB(char *buf, unsigned int total_read, struct TCP_Server_Info *server)
329 struct smb_hdr *smb = (struct smb_hdr *)buf;
330 __u32 rfclen = be32_to_cpu(smb->smb_buf_length);
331 __u32 clc_len; /* calculated length */
332 cifs_dbg(FYI, "checkSMB Length: 0x%x, smb_buf_length: 0x%x\n",
335 /* is this frame too small to even get to a BCC? */
336 if (total_read < 2 + sizeof(struct smb_hdr)) {
337 if ((total_read >= sizeof(struct smb_hdr) - 1)
338 && (smb->Status.CifsError != 0)) {
339 /* it's an error return */
341 /* some error cases do not return wct and bcc */
343 } else if ((total_read == sizeof(struct smb_hdr) + 1) &&
344 (smb->WordCount == 0)) {
345 char *tmp = (char *)smb;
346 /* Need to work around a bug in two servers here */
347 /* First, check if the part of bcc they sent was zero */
348 if (tmp[sizeof(struct smb_hdr)] == 0) {
349 /* some servers return only half of bcc
350 * on simple responses (wct, bcc both zero)
351 * in particular have seen this on
352 * ulogoffX and FindClose. This leaves
353 * one byte of bcc potentially unitialized
355 /* zero rest of bcc */
356 tmp[sizeof(struct smb_hdr)+1] = 0;
359 cifs_dbg(VFS, "rcvd invalid byte count (bcc)\n");
361 cifs_dbg(VFS, "Length less than smb header size\n");
364 } else if (total_read < sizeof(*smb) + 2 * smb->WordCount) {
365 cifs_dbg(VFS, "%s: can't read BCC due to invalid WordCount(%u)\n",
366 __func__, smb->WordCount);
370 /* otherwise, there is enough to get to the BCC */
371 if (check_smb_hdr(smb))
373 clc_len = smbCalcSize(smb);
375 if (4 + rfclen != total_read) {
376 cifs_dbg(VFS, "Length read does not match RFC1001 length %d\n",
381 if (4 + rfclen != clc_len) {
382 __u16 mid = get_mid(smb);
383 /* check if bcc wrapped around for large read responses */
384 if ((rfclen > 64 * 1024) && (rfclen > clc_len)) {
385 /* check if lengths match mod 64K */
386 if (((4 + rfclen) & 0xFFFF) == (clc_len & 0xFFFF))
387 return 0; /* bcc wrapped */
389 cifs_dbg(FYI, "Calculated size %u vs length %u mismatch for mid=%u\n",
390 clc_len, 4 + rfclen, mid);
392 if (4 + rfclen < clc_len) {
393 cifs_dbg(VFS, "RFC1001 size %u smaller than SMB for mid=%u\n",
396 } else if (rfclen > clc_len + 512) {
398 * Some servers (Windows XP in particular) send more
399 * data than the lengths in the SMB packet would
400 * indicate on certain calls (byte range locks and
401 * trans2 find first calls in particular). While the
402 * client can handle such a frame by ignoring the
403 * trailing data, we choose limit the amount of extra
406 cifs_dbg(VFS, "RFC1001 size %u more than 512 bytes larger than SMB for mid=%u\n",
415 is_valid_oplock_break(char *buffer, struct TCP_Server_Info *srv)
417 struct smb_hdr *buf = (struct smb_hdr *)buffer;
418 struct smb_com_lock_req *pSMB = (struct smb_com_lock_req *)buf;
419 struct TCP_Server_Info *pserver;
420 struct cifs_ses *ses;
421 struct cifs_tcon *tcon;
422 struct cifsInodeInfo *pCifsInode;
423 struct cifsFileInfo *netfile;
425 cifs_dbg(FYI, "Checking for oplock break or dnotify response\n");
426 if ((pSMB->hdr.Command == SMB_COM_NT_TRANSACT) &&
427 (pSMB->hdr.Flags & SMBFLG_RESPONSE)) {
428 struct smb_com_transaction_change_notify_rsp *pSMBr =
429 (struct smb_com_transaction_change_notify_rsp *)buf;
430 struct file_notify_information *pnotify;
431 __u32 data_offset = 0;
432 size_t len = srv->total_read - sizeof(pSMBr->hdr.smb_buf_length);
434 if (get_bcc(buf) > sizeof(struct file_notify_information)) {
435 data_offset = le32_to_cpu(pSMBr->DataOffset);
438 len - sizeof(struct file_notify_information)) {
439 cifs_dbg(FYI, "Invalid data_offset %u\n",
443 pnotify = (struct file_notify_information *)
444 ((char *)&pSMBr->hdr.Protocol + data_offset);
445 cifs_dbg(FYI, "dnotify on %s Action: 0x%x\n",
446 pnotify->FileName, pnotify->Action);
447 /* cifs_dump_mem("Rcvd notify Data: ",buf,
448 sizeof(struct smb_hdr)+60); */
451 if (pSMBr->hdr.Status.CifsError) {
452 cifs_dbg(FYI, "notify err 0x%x\n",
453 pSMBr->hdr.Status.CifsError);
458 if (pSMB->hdr.Command != SMB_COM_LOCKING_ANDX)
460 if (pSMB->hdr.Flags & SMBFLG_RESPONSE) {
461 /* no sense logging error on invalid handle on oplock
462 break - harmless race between close request and oplock
463 break response is expected from time to time writing out
464 large dirty files cached on the client */
465 if ((NT_STATUS_INVALID_HANDLE) ==
466 le32_to_cpu(pSMB->hdr.Status.CifsError)) {
467 cifs_dbg(FYI, "Invalid handle on oplock break\n");
469 } else if (ERRbadfid ==
470 le16_to_cpu(pSMB->hdr.Status.DosError.Error)) {
473 return false; /* on valid oplock brk we get "request" */
476 if (pSMB->hdr.WordCount != 8)
479 cifs_dbg(FYI, "oplock type 0x%x level 0x%x\n",
480 pSMB->LockType, pSMB->OplockLevel);
481 if (!(pSMB->LockType & LOCKING_ANDX_OPLOCK_RELEASE))
484 /* If server is a channel, select the primary channel */
485 pserver = SERVER_IS_CHAN(srv) ? srv->primary_server : srv;
487 /* look up tcon based on tid & uid */
488 spin_lock(&cifs_tcp_ses_lock);
489 list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
490 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
491 if (tcon->tid != buf->Tid)
494 cifs_stats_inc(&tcon->stats.cifs_stats.num_oplock_brks);
495 spin_lock(&tcon->open_file_lock);
496 list_for_each_entry(netfile, &tcon->openFileList, tlist) {
497 if (pSMB->Fid != netfile->fid.netfid)
500 cifs_dbg(FYI, "file id match, oplock break\n");
501 pCifsInode = CIFS_I(d_inode(netfile->dentry));
503 set_bit(CIFS_INODE_PENDING_OPLOCK_BREAK,
506 netfile->oplock_epoch = 0;
507 netfile->oplock_level = pSMB->OplockLevel;
508 netfile->oplock_break_cancelled = false;
509 cifs_queue_oplock_break(netfile);
511 spin_unlock(&tcon->open_file_lock);
512 spin_unlock(&cifs_tcp_ses_lock);
515 spin_unlock(&tcon->open_file_lock);
516 spin_unlock(&cifs_tcp_ses_lock);
517 cifs_dbg(FYI, "No matching file for oplock break\n");
521 spin_unlock(&cifs_tcp_ses_lock);
522 cifs_dbg(FYI, "Can not process oplock break for non-existent connection\n");
527 dump_smb(void *buf, int smb_buf_length)
532 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_NONE, 8, 2, buf,
533 smb_buf_length, true);
537 cifs_autodisable_serverino(struct cifs_sb_info *cifs_sb)
539 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) {
540 struct cifs_tcon *tcon = NULL;
542 if (cifs_sb->master_tlink)
543 tcon = cifs_sb_master_tcon(cifs_sb);
545 cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_SERVER_INUM;
546 cifs_sb->mnt_cifs_serverino_autodisabled = true;
547 cifs_dbg(VFS, "Autodisabling the use of server inode numbers on %s\n",
548 tcon ? tcon->tree_name : "new server");
549 cifs_dbg(VFS, "The server doesn't seem to support them properly or the files might be on different servers (DFS)\n");
550 cifs_dbg(VFS, "Hardlinks will not be recognized on this mount. Consider mounting with the \"noserverino\" option to silence this message.\n");
555 void cifs_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock)
559 if (oplock == OPLOCK_EXCLUSIVE) {
560 cinode->oplock = CIFS_CACHE_WRITE_FLG | CIFS_CACHE_READ_FLG;
561 cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
562 &cinode->netfs.inode);
563 } else if (oplock == OPLOCK_READ) {
564 cinode->oplock = CIFS_CACHE_READ_FLG;
565 cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
566 &cinode->netfs.inode);
572 * We wait for oplock breaks to be processed before we attempt to perform
575 int cifs_get_writer(struct cifsInodeInfo *cinode)
580 rc = wait_on_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK,
585 spin_lock(&cinode->writers_lock);
586 if (!cinode->writers)
587 set_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
589 /* Check to see if we have started servicing an oplock break */
590 if (test_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags)) {
592 if (cinode->writers == 0) {
593 clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
594 wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
596 spin_unlock(&cinode->writers_lock);
599 spin_unlock(&cinode->writers_lock);
603 void cifs_put_writer(struct cifsInodeInfo *cinode)
605 spin_lock(&cinode->writers_lock);
607 if (cinode->writers == 0) {
608 clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
609 wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
611 spin_unlock(&cinode->writers_lock);
615 * cifs_queue_oplock_break - queue the oplock break handler for cfile
616 * @cfile: The file to break the oplock on
618 * This function is called from the demultiplex thread when it
619 * receives an oplock break for @cfile.
621 * Assumes the tcon->open_file_lock is held.
622 * Assumes cfile->file_info_lock is NOT held.
624 void cifs_queue_oplock_break(struct cifsFileInfo *cfile)
627 * Bump the handle refcount now while we hold the
628 * open_file_lock to enforce the validity of it for the oplock
629 * break handler. The matching put is done at the end of the
632 cifsFileInfo_get(cfile);
634 queue_work(cifsoplockd_wq, &cfile->oplock_break);
637 void cifs_done_oplock_break(struct cifsInodeInfo *cinode)
639 clear_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags);
640 wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK);
644 backup_cred(struct cifs_sb_info *cifs_sb)
646 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPUID) {
647 if (uid_eq(cifs_sb->ctx->backupuid, current_fsuid()))
650 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPGID) {
651 if (in_group_p(cifs_sb->ctx->backupgid))
659 cifs_del_pending_open(struct cifs_pending_open *open)
661 spin_lock(&tlink_tcon(open->tlink)->open_file_lock);
662 list_del(&open->olist);
663 spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
667 cifs_add_pending_open_locked(struct cifs_fid *fid, struct tcon_link *tlink,
668 struct cifs_pending_open *open)
670 memcpy(open->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
671 open->oplock = CIFS_OPLOCK_NO_CHANGE;
673 fid->pending_open = open;
674 list_add_tail(&open->olist, &tlink_tcon(tlink)->pending_opens);
678 cifs_add_pending_open(struct cifs_fid *fid, struct tcon_link *tlink,
679 struct cifs_pending_open *open)
681 spin_lock(&tlink_tcon(tlink)->open_file_lock);
682 cifs_add_pending_open_locked(fid, tlink, open);
683 spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
687 * Critical section which runs after acquiring deferred_lock.
688 * As there is no reference count on cifs_deferred_close, pdclose
689 * should not be used outside deferred_lock.
692 cifs_is_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close **pdclose)
694 struct cifs_deferred_close *dclose;
696 list_for_each_entry(dclose, &CIFS_I(d_inode(cfile->dentry))->deferred_closes, dlist) {
697 if ((dclose->netfid == cfile->fid.netfid) &&
698 (dclose->persistent_fid == cfile->fid.persistent_fid) &&
699 (dclose->volatile_fid == cfile->fid.volatile_fid)) {
708 * Critical section which runs after acquiring deferred_lock.
711 cifs_add_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close *dclose)
713 bool is_deferred = false;
714 struct cifs_deferred_close *pdclose;
716 is_deferred = cifs_is_deferred_close(cfile, &pdclose);
722 dclose->tlink = cfile->tlink;
723 dclose->netfid = cfile->fid.netfid;
724 dclose->persistent_fid = cfile->fid.persistent_fid;
725 dclose->volatile_fid = cfile->fid.volatile_fid;
726 list_add_tail(&dclose->dlist, &CIFS_I(d_inode(cfile->dentry))->deferred_closes);
730 * Critical section which runs after acquiring deferred_lock.
733 cifs_del_deferred_close(struct cifsFileInfo *cfile)
735 bool is_deferred = false;
736 struct cifs_deferred_close *dclose;
738 is_deferred = cifs_is_deferred_close(cfile, &dclose);
741 list_del(&dclose->dlist);
746 cifs_close_deferred_file(struct cifsInodeInfo *cifs_inode)
748 struct cifsFileInfo *cfile = NULL;
749 struct file_list *tmp_list, *tmp_next_list;
750 struct list_head file_head;
752 if (cifs_inode == NULL)
755 INIT_LIST_HEAD(&file_head);
756 spin_lock(&cifs_inode->open_file_lock);
757 list_for_each_entry(cfile, &cifs_inode->openFileList, flist) {
758 if (delayed_work_pending(&cfile->deferred)) {
759 if (cancel_delayed_work(&cfile->deferred)) {
760 spin_lock(&cifs_inode->deferred_lock);
761 cifs_del_deferred_close(cfile);
762 spin_unlock(&cifs_inode->deferred_lock);
764 tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
765 if (tmp_list == NULL)
767 tmp_list->cfile = cfile;
768 list_add_tail(&tmp_list->list, &file_head);
772 spin_unlock(&cifs_inode->open_file_lock);
774 list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
775 _cifsFileInfo_put(tmp_list->cfile, false, false);
776 list_del(&tmp_list->list);
782 cifs_close_all_deferred_files(struct cifs_tcon *tcon)
784 struct cifsFileInfo *cfile;
785 struct file_list *tmp_list, *tmp_next_list;
786 struct list_head file_head;
788 INIT_LIST_HEAD(&file_head);
789 spin_lock(&tcon->open_file_lock);
790 list_for_each_entry(cfile, &tcon->openFileList, tlist) {
791 if (delayed_work_pending(&cfile->deferred)) {
792 if (cancel_delayed_work(&cfile->deferred)) {
793 spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
794 cifs_del_deferred_close(cfile);
795 spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
797 tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
798 if (tmp_list == NULL)
800 tmp_list->cfile = cfile;
801 list_add_tail(&tmp_list->list, &file_head);
805 spin_unlock(&tcon->open_file_lock);
807 list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
808 _cifsFileInfo_put(tmp_list->cfile, true, false);
809 list_del(&tmp_list->list);
814 cifs_close_deferred_file_under_dentry(struct cifs_tcon *tcon, const char *path)
816 struct cifsFileInfo *cfile;
817 struct file_list *tmp_list, *tmp_next_list;
818 struct list_head file_head;
820 const char *full_path;
822 INIT_LIST_HEAD(&file_head);
823 page = alloc_dentry_path();
824 spin_lock(&tcon->open_file_lock);
825 list_for_each_entry(cfile, &tcon->openFileList, tlist) {
826 full_path = build_path_from_dentry(cfile->dentry, page);
827 if (strstr(full_path, path)) {
828 if (delayed_work_pending(&cfile->deferred)) {
829 if (cancel_delayed_work(&cfile->deferred)) {
830 spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
831 cifs_del_deferred_close(cfile);
832 spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
834 tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
835 if (tmp_list == NULL)
837 tmp_list->cfile = cfile;
838 list_add_tail(&tmp_list->list, &file_head);
843 spin_unlock(&tcon->open_file_lock);
845 list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
846 _cifsFileInfo_put(tmp_list->cfile, true, false);
847 list_del(&tmp_list->list);
850 free_dentry_path(page);
854 * If a dentry has been deleted, all corresponding open handles should know that
855 * so that we do not defer close them.
857 void cifs_mark_open_handles_for_deleted_file(struct inode *inode,
860 struct cifsFileInfo *cfile;
862 const char *full_path;
863 struct cifsInodeInfo *cinode = CIFS_I(inode);
865 page = alloc_dentry_path();
866 spin_lock(&cinode->open_file_lock);
869 * note: we need to construct path from dentry and compare only if the
870 * inode has any hardlinks. When number of hardlinks is 1, we can just
871 * mark all open handles since they are going to be from the same file.
873 if (inode->i_nlink > 1) {
874 list_for_each_entry(cfile, &cinode->openFileList, flist) {
875 full_path = build_path_from_dentry(cfile->dentry, page);
876 if (!IS_ERR(full_path) && strcmp(full_path, path) == 0)
877 cfile->status_file_deleted = true;
880 list_for_each_entry(cfile, &cinode->openFileList, flist)
881 cfile->status_file_deleted = true;
883 spin_unlock(&cinode->open_file_lock);
884 free_dentry_path(page);
887 /* parses DFS referral V3 structure
888 * caller is responsible for freeing target_nodes
891 * - on failure - errno
894 parse_dfs_referrals(struct get_dfs_referral_rsp *rsp, u32 rsp_size,
895 unsigned int *num_of_nodes,
896 struct dfs_info3_param **target_nodes,
897 const struct nls_table *nls_codepage, int remap,
898 const char *searchName, bool is_unicode)
902 struct dfs_referral_level_3 *ref;
904 *num_of_nodes = le16_to_cpu(rsp->NumberOfReferrals);
906 if (*num_of_nodes < 1) {
907 cifs_dbg(VFS, "num_referrals: must be at least > 0, but we get num_referrals = %d\n",
910 goto parse_DFS_referrals_exit;
913 ref = (struct dfs_referral_level_3 *) &(rsp->referrals);
914 if (ref->VersionNumber != cpu_to_le16(3)) {
915 cifs_dbg(VFS, "Referrals of V%d version are not supported, should be V3\n",
916 le16_to_cpu(ref->VersionNumber));
918 goto parse_DFS_referrals_exit;
921 /* get the upper boundary of the resp buffer */
922 data_end = (char *)rsp + rsp_size;
924 cifs_dbg(FYI, "num_referrals: %d dfs flags: 0x%x ...\n",
925 *num_of_nodes, le32_to_cpu(rsp->DFSFlags));
927 *target_nodes = kcalloc(*num_of_nodes, sizeof(struct dfs_info3_param),
929 if (*target_nodes == NULL) {
931 goto parse_DFS_referrals_exit;
934 /* collect necessary data from referrals */
935 for (i = 0; i < *num_of_nodes; i++) {
938 struct dfs_info3_param *node = (*target_nodes)+i;
940 node->flags = le32_to_cpu(rsp->DFSFlags);
942 __le16 *tmp = kmalloc(strlen(searchName)*2 + 2,
946 goto parse_DFS_referrals_exit;
948 cifsConvertToUTF16((__le16 *) tmp, searchName,
949 PATH_MAX, nls_codepage, remap);
950 node->path_consumed = cifs_utf16_bytes(tmp,
951 le16_to_cpu(rsp->PathConsumed),
955 node->path_consumed = le16_to_cpu(rsp->PathConsumed);
957 node->server_type = le16_to_cpu(ref->ServerType);
958 node->ref_flag = le16_to_cpu(ref->ReferralEntryFlags);
961 temp = (char *)ref + le16_to_cpu(ref->DfsPathOffset);
962 max_len = data_end - temp;
963 node->path_name = cifs_strndup_from_utf16(temp, max_len,
964 is_unicode, nls_codepage);
965 if (!node->path_name) {
967 goto parse_DFS_referrals_exit;
970 /* copy link target UNC */
971 temp = (char *)ref + le16_to_cpu(ref->NetworkAddressOffset);
972 max_len = data_end - temp;
973 node->node_name = cifs_strndup_from_utf16(temp, max_len,
974 is_unicode, nls_codepage);
975 if (!node->node_name) {
977 goto parse_DFS_referrals_exit;
980 node->ttl = le32_to_cpu(ref->TimeToLive);
985 parse_DFS_referrals_exit:
987 free_dfs_info_array(*target_nodes, *num_of_nodes);
988 *target_nodes = NULL;
994 struct cifs_aio_ctx *
995 cifs_aio_ctx_alloc(void)
997 struct cifs_aio_ctx *ctx;
1000 * Must use kzalloc to initialize ctx->bv to NULL and ctx->direct_io
1001 * to false so that we know when we have to unreference pages within
1002 * cifs_aio_ctx_release()
1004 ctx = kzalloc(sizeof(struct cifs_aio_ctx), GFP_KERNEL);
1008 INIT_LIST_HEAD(&ctx->list);
1009 mutex_init(&ctx->aio_mutex);
1010 init_completion(&ctx->done);
1011 kref_init(&ctx->refcount);
1016 cifs_aio_ctx_release(struct kref *refcount)
1018 struct cifs_aio_ctx *ctx = container_of(refcount,
1019 struct cifs_aio_ctx, refcount);
1021 cifsFileInfo_put(ctx->cfile);
1024 * ctx->bv is only set if setup_aio_ctx_iter() was call successfuly
1025 * which means that iov_iter_extract_pages() was a success and thus
1026 * that we may have references or pins on pages that we need to
1030 if (ctx->should_dirty || ctx->bv_need_unpin) {
1033 for (i = 0; i < ctx->nr_pinned_pages; i++) {
1034 struct page *page = ctx->bv[i].bv_page;
1036 if (ctx->should_dirty)
1037 set_page_dirty(page);
1038 if (ctx->bv_need_unpin)
1039 unpin_user_page(page);
1049 * cifs_alloc_hash - allocate hash and hash context together
1050 * @name: The name of the crypto hash algo
1051 * @sdesc: SHASH descriptor where to put the pointer to the hash TFM
1053 * The caller has to make sure @sdesc is initialized to either NULL or
1054 * a valid context. It can be freed via cifs_free_hash().
1057 cifs_alloc_hash(const char *name, struct shash_desc **sdesc)
1060 struct crypto_shash *alg = NULL;
1065 alg = crypto_alloc_shash(name, 0, 0);
1067 cifs_dbg(VFS, "Could not allocate shash TFM '%s'\n", name);
1073 *sdesc = kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(alg), GFP_KERNEL);
1074 if (*sdesc == NULL) {
1075 cifs_dbg(VFS, "no memory left to allocate shash TFM '%s'\n", name);
1076 crypto_free_shash(alg);
1080 (*sdesc)->tfm = alg;
1085 * cifs_free_hash - free hash and hash context together
1086 * @sdesc: Where to find the pointer to the hash TFM
1088 * Freeing a NULL descriptor is safe.
1091 cifs_free_hash(struct shash_desc **sdesc)
1093 if (unlikely(!sdesc) || !*sdesc)
1096 if ((*sdesc)->tfm) {
1097 crypto_free_shash((*sdesc)->tfm);
1098 (*sdesc)->tfm = NULL;
1101 kfree_sensitive(*sdesc);
1105 void extract_unc_hostname(const char *unc, const char **h, size_t *len)
1109 /* skip initial slashes */
1110 while (*unc && (*unc == '\\' || *unc == '/'))
1115 while (*end && !(*end == '\\' || *end == '/'))
1123 * copy_path_name - copy src path to dst, possibly truncating
1124 * @dst: The destination buffer
1125 * @src: The source name
1127 * returns number of bytes written (including trailing nul)
1129 int copy_path_name(char *dst, const char *src)
1134 * PATH_MAX includes nul, so if strlen(src) >= PATH_MAX it
1135 * will truncate and strlen(dst) will be PATH_MAX-1
1137 name_len = strscpy(dst, src, PATH_MAX);
1138 if (WARN_ON_ONCE(name_len < 0))
1139 name_len = PATH_MAX-1;
1141 /* we count the trailing nul */
1146 struct super_cb_data {
1148 struct super_block *sb;
1151 static void tcon_super_cb(struct super_block *sb, void *arg)
1153 struct super_cb_data *sd = arg;
1154 struct cifs_sb_info *cifs_sb;
1155 struct cifs_tcon *t1 = sd->data, *t2;
1160 cifs_sb = CIFS_SB(sb);
1161 t2 = cifs_sb_master_tcon(cifs_sb);
1163 spin_lock(&t2->tc_lock);
1164 if (t1->ses == t2->ses &&
1165 t1->ses->server == t2->ses->server &&
1166 t2->origin_fullpath &&
1167 dfs_src_pathname_equal(t2->origin_fullpath, t1->origin_fullpath))
1169 spin_unlock(&t2->tc_lock);
1172 static struct super_block *__cifs_get_super(void (*f)(struct super_block *, void *),
1175 struct super_cb_data sd = {
1179 struct file_system_type **fs_type = (struct file_system_type *[]) {
1180 &cifs_fs_type, &smb3_fs_type, NULL,
1183 for (; *fs_type; fs_type++) {
1184 iterate_supers_type(*fs_type, f, &sd);
1187 * Grab an active reference in order to prevent automounts (DFS links)
1188 * of expiring and then freeing up our cifs superblock pointer while
1189 * we're doing failover.
1191 cifs_sb_active(sd.sb);
1195 pr_warn_once("%s: could not find dfs superblock\n", __func__);
1196 return ERR_PTR(-EINVAL);
1199 static void __cifs_put_super(struct super_block *sb)
1201 if (!IS_ERR_OR_NULL(sb))
1202 cifs_sb_deactive(sb);
1205 struct super_block *cifs_get_dfs_tcon_super(struct cifs_tcon *tcon)
1207 spin_lock(&tcon->tc_lock);
1208 if (!tcon->origin_fullpath) {
1209 spin_unlock(&tcon->tc_lock);
1210 return ERR_PTR(-ENOENT);
1212 spin_unlock(&tcon->tc_lock);
1213 return __cifs_get_super(tcon_super_cb, tcon);
1216 void cifs_put_tcp_super(struct super_block *sb)
1218 __cifs_put_super(sb);
1221 #ifdef CONFIG_CIFS_DFS_UPCALL
1222 int match_target_ip(struct TCP_Server_Info *server,
1223 const char *share, size_t share_len,
1228 struct sockaddr_storage ss;
1232 target = kzalloc(share_len + 3, GFP_KERNEL);
1236 scnprintf(target, share_len + 3, "\\\\%.*s", (int)share_len, share);
1238 cifs_dbg(FYI, "%s: target name: %s\n", __func__, target + 2);
1240 rc = dns_resolve_server_name_to_ip(target, (struct sockaddr *)&ss, NULL);
1246 spin_lock(&server->srv_lock);
1247 *result = cifs_match_ipaddr((struct sockaddr *)&server->dstaddr, (struct sockaddr *)&ss);
1248 spin_unlock(&server->srv_lock);
1249 cifs_dbg(FYI, "%s: ip addresses match: %u\n", __func__, *result);
1253 int cifs_update_super_prepath(struct cifs_sb_info *cifs_sb, char *prefix)
1257 kfree(cifs_sb->prepath);
1258 cifs_sb->prepath = NULL;
1260 if (prefix && *prefix) {
1261 cifs_sb->prepath = cifs_sanitize_prepath(prefix, GFP_ATOMIC);
1262 if (IS_ERR(cifs_sb->prepath)) {
1263 rc = PTR_ERR(cifs_sb->prepath);
1264 cifs_sb->prepath = NULL;
1267 if (cifs_sb->prepath)
1268 convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb));
1271 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
1276 * Handle weird Windows SMB server behaviour. It responds with
1277 * STATUS_OBJECT_NAME_INVALID code to SMB2 QUERY_INFO request for
1278 * "\<server>\<dfsname>\<linkpath>" DFS reference, where <dfsname> contains
1279 * non-ASCII unicode symbols.
1281 int cifs_inval_name_dfs_link_error(const unsigned int xid,
1282 struct cifs_tcon *tcon,
1283 struct cifs_sb_info *cifs_sb,
1284 const char *full_path,
1287 struct cifs_ses *ses = tcon->ses;
1295 * Fast path - skip check when @full_path doesn't have a prefix path to
1296 * look up or tcon is not DFS.
1298 if (strlen(full_path) < 2 || !cifs_sb ||
1299 (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
1303 spin_lock(&tcon->tc_lock);
1304 if (!tcon->origin_fullpath) {
1305 spin_unlock(&tcon->tc_lock);
1308 spin_unlock(&tcon->tc_lock);
1311 * Slow path - tcon is DFS and @full_path has prefix path, so attempt
1312 * to get a referral to figure out whether it is an DFS link.
1314 len = strnlen(tcon->tree_name, MAX_TREE_SIZE + 1) + strlen(full_path) + 1;
1315 path = kmalloc(len, GFP_KERNEL);
1319 scnprintf(path, len, "%s%s", tcon->tree_name, full_path);
1320 ref_path = dfs_cache_canonical_path(path + 1, cifs_sb->local_nls,
1321 cifs_remap(cifs_sb));
1324 if (IS_ERR(ref_path)) {
1325 if (PTR_ERR(ref_path) != -EINVAL)
1326 return PTR_ERR(ref_path);
1328 struct dfs_info3_param *refs = NULL;
1332 * XXX: we are not using dfs_cache_find() here because we might
1333 * end up filling all the DFS cache and thus potentially
1334 * removing cached DFS targets that the client would eventually
1335 * need during failover.
1337 ses = CIFS_DFS_ROOT_SES(ses);
1338 if (ses->server->ops->get_dfs_refer &&
1339 !ses->server->ops->get_dfs_refer(xid, ses, ref_path, &refs,
1340 &num_refs, cifs_sb->local_nls,
1341 cifs_remap(cifs_sb)))
1342 *islink = refs[0].server_type == DFS_TYPE_LINK;
1343 free_dfs_info_array(refs, num_refs);
1350 int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry)
1355 spin_lock(&server->srv_lock);
1356 if (server->tcpStatus != CifsNeedReconnect) {
1357 spin_unlock(&server->srv_lock);
1360 timeout *= server->nr_targets;
1361 spin_unlock(&server->srv_lock);
1364 * Give demultiplex thread up to 10 seconds to each target available for
1365 * reconnect -- should be greater than cifs socket timeout which is 7
1368 * On "soft" mounts we wait once. Hard mounts keep retrying until
1369 * process is killed or server comes back on-line.
1372 rc = wait_event_interruptible_timeout(server->response_q,
1373 (server->tcpStatus != CifsNeedReconnect),
1376 cifs_dbg(FYI, "%s: aborting reconnect due to received signal\n",
1378 return -ERESTARTSYS;
1381 /* are we still trying to reconnect? */
1382 spin_lock(&server->srv_lock);
1383 if (server->tcpStatus != CifsNeedReconnect) {
1384 spin_unlock(&server->srv_lock);
1387 spin_unlock(&server->srv_lock);
1390 cifs_dbg(FYI, "%s: gave up waiting on reconnect\n", __func__);