]> Pileus Git - ~andy/linux/blob - drivers/block/drbd/drbd_nl.c
drbd: use the cached meta_dev_idx
[~andy/linux] / drivers / block / drbd / drbd_nl.c
1 /*
2    drbd_nl.c
3
4    This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
5
6    Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
7    Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
8    Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
9
10    drbd is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2, or (at your option)
13    any later version.
14
15    drbd is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with drbd; see the file COPYING.  If not, write to
22    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24  */
25
26 #include <linux/module.h>
27 #include <linux/drbd.h>
28 #include <linux/in.h>
29 #include <linux/fs.h>
30 #include <linux/file.h>
31 #include <linux/slab.h>
32 #include <linux/blkpg.h>
33 #include <linux/cpumask.h>
34 #include "drbd_int.h"
35 #include "drbd_req.h"
36 #include "drbd_wrappers.h"
37 #include <asm/unaligned.h>
38 #include <linux/drbd_limits.h>
39 #include <linux/kthread.h>
40
41 #include <net/genetlink.h>
42
43 /* .doit */
44 // int drbd_adm_create_resource(struct sk_buff *skb, struct genl_info *info);
45 // int drbd_adm_delete_resource(struct sk_buff *skb, struct genl_info *info);
46
47 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info);
48 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info);
49
50 int drbd_adm_new_resource(struct sk_buff *skb, struct genl_info *info);
51 int drbd_adm_del_resource(struct sk_buff *skb, struct genl_info *info);
52 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info);
53
54 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info);
55 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info);
56 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info);
57 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info);
58 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info);
59 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info);
60 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info);
61 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info);
62 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info);
63 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info);
64 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info);
65 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info);
66 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info);
67 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info);
68 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info);
69 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info);
70 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info);
71 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info);
72 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info);
73 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info);
74 /* .dumpit */
75 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb);
76
77 #include <linux/drbd_genl_api.h>
78 #include "drbd_nla.h"
79 #include <linux/genl_magic_func.h>
80
81 /* used blkdev_get_by_path, to claim our meta data device(s) */
82 static char *drbd_m_holder = "Hands off! this is DRBD's meta data device.";
83
84 /* Configuration is strictly serialized, because generic netlink message
85  * processing is strictly serialized by the genl_lock().
86  * Which means we can use one static global drbd_config_context struct.
87  */
88 static struct drbd_config_context {
89         /* assigned from drbd_genlmsghdr */
90         unsigned int minor;
91         /* assigned from request attributes, if present */
92         unsigned int volume;
93 #define VOLUME_UNSPECIFIED              (-1U)
94         /* pointer into the request skb,
95          * limited lifetime! */
96         char *resource_name;
97         struct nlattr *my_addr;
98         struct nlattr *peer_addr;
99
100         /* reply buffer */
101         struct sk_buff *reply_skb;
102         /* pointer into reply buffer */
103         struct drbd_genlmsghdr *reply_dh;
104         /* resolved from attributes, if possible */
105         struct drbd_conf *mdev;
106         struct drbd_tconn *tconn;
107 } adm_ctx;
108
109 static void drbd_adm_send_reply(struct sk_buff *skb, struct genl_info *info)
110 {
111         genlmsg_end(skb, genlmsg_data(nlmsg_data(nlmsg_hdr(skb))));
112         if (genlmsg_reply(skb, info))
113                 printk(KERN_ERR "drbd: error sending genl reply\n");
114 }
115
116 /* Used on a fresh "drbd_adm_prepare"d reply_skb, this cannot fail: The only
117  * reason it could fail was no space in skb, and there are 4k available. */
118 int drbd_msg_put_info(const char *info)
119 {
120         struct sk_buff *skb = adm_ctx.reply_skb;
121         struct nlattr *nla;
122         int err = -EMSGSIZE;
123
124         if (!info || !info[0])
125                 return 0;
126
127         nla = nla_nest_start(skb, DRBD_NLA_CFG_REPLY);
128         if (!nla)
129                 return err;
130
131         err = nla_put_string(skb, T_info_text, info);
132         if (err) {
133                 nla_nest_cancel(skb, nla);
134                 return err;
135         } else
136                 nla_nest_end(skb, nla);
137         return 0;
138 }
139
140 /* This would be a good candidate for a "pre_doit" hook,
141  * and per-family private info->pointers.
142  * But we need to stay compatible with older kernels.
143  * If it returns successfully, adm_ctx members are valid.
144  */
145 #define DRBD_ADM_NEED_MINOR     1
146 #define DRBD_ADM_NEED_RESOURCE  2
147 #define DRBD_ADM_NEED_CONNECTION 4
148 static int drbd_adm_prepare(struct sk_buff *skb, struct genl_info *info,
149                 unsigned flags)
150 {
151         struct drbd_genlmsghdr *d_in = info->userhdr;
152         const u8 cmd = info->genlhdr->cmd;
153         int err;
154
155         memset(&adm_ctx, 0, sizeof(adm_ctx));
156
157         /* genl_rcv_msg only checks for CAP_NET_ADMIN on "GENL_ADMIN_PERM" :( */
158         if (cmd != DRBD_ADM_GET_STATUS && !capable(CAP_NET_ADMIN))
159                return -EPERM;
160
161         adm_ctx.reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
162         if (!adm_ctx.reply_skb) {
163                 err = -ENOMEM;
164                 goto fail;
165         }
166
167         adm_ctx.reply_dh = genlmsg_put_reply(adm_ctx.reply_skb,
168                                         info, &drbd_genl_family, 0, cmd);
169         /* put of a few bytes into a fresh skb of >= 4k will always succeed.
170          * but anyways */
171         if (!adm_ctx.reply_dh) {
172                 err = -ENOMEM;
173                 goto fail;
174         }
175
176         adm_ctx.reply_dh->minor = d_in->minor;
177         adm_ctx.reply_dh->ret_code = NO_ERROR;
178
179         adm_ctx.volume = VOLUME_UNSPECIFIED;
180         if (info->attrs[DRBD_NLA_CFG_CONTEXT]) {
181                 struct nlattr *nla;
182                 /* parse and validate only */
183                 err = drbd_cfg_context_from_attrs(NULL, info);
184                 if (err)
185                         goto fail;
186
187                 /* It was present, and valid,
188                  * copy it over to the reply skb. */
189                 err = nla_put_nohdr(adm_ctx.reply_skb,
190                                 info->attrs[DRBD_NLA_CFG_CONTEXT]->nla_len,
191                                 info->attrs[DRBD_NLA_CFG_CONTEXT]);
192                 if (err)
193                         goto fail;
194
195                 /* and assign stuff to the global adm_ctx */
196                 nla = nested_attr_tb[__nla_type(T_ctx_volume)];
197                 if (nla)
198                         adm_ctx.volume = nla_get_u32(nla);
199                 nla = nested_attr_tb[__nla_type(T_ctx_resource_name)];
200                 if (nla)
201                         adm_ctx.resource_name = nla_data(nla);
202                 adm_ctx.my_addr = nested_attr_tb[__nla_type(T_ctx_my_addr)];
203                 adm_ctx.peer_addr = nested_attr_tb[__nla_type(T_ctx_peer_addr)];
204                 if ((adm_ctx.my_addr &&
205                      nla_len(adm_ctx.my_addr) > sizeof(adm_ctx.tconn->my_addr)) ||
206                     (adm_ctx.peer_addr &&
207                      nla_len(adm_ctx.peer_addr) > sizeof(adm_ctx.tconn->peer_addr))) {
208                         err = -EINVAL;
209                         goto fail;
210                 }
211         }
212
213         adm_ctx.minor = d_in->minor;
214         adm_ctx.mdev = minor_to_mdev(d_in->minor);
215         adm_ctx.tconn = conn_get_by_name(adm_ctx.resource_name);
216
217         if (!adm_ctx.mdev && (flags & DRBD_ADM_NEED_MINOR)) {
218                 drbd_msg_put_info("unknown minor");
219                 return ERR_MINOR_INVALID;
220         }
221         if (!adm_ctx.tconn && (flags & DRBD_ADM_NEED_RESOURCE)) {
222                 drbd_msg_put_info("unknown resource");
223                 return ERR_INVALID_REQUEST;
224         }
225
226         if (flags & DRBD_ADM_NEED_CONNECTION) {
227                 if (adm_ctx.tconn && !(flags & DRBD_ADM_NEED_RESOURCE)) {
228                         drbd_msg_put_info("no resource name expected");
229                         return ERR_INVALID_REQUEST;
230                 }
231                 if (adm_ctx.mdev) {
232                         drbd_msg_put_info("no minor number expected");
233                         return ERR_INVALID_REQUEST;
234                 }
235                 if (adm_ctx.my_addr && adm_ctx.peer_addr)
236                         adm_ctx.tconn = conn_get_by_addrs(nla_data(adm_ctx.my_addr),
237                                                           nla_len(adm_ctx.my_addr),
238                                                           nla_data(adm_ctx.peer_addr),
239                                                           nla_len(adm_ctx.peer_addr));
240                 if (!adm_ctx.tconn) {
241                         drbd_msg_put_info("unknown connection");
242                         return ERR_INVALID_REQUEST;
243                 }
244         }
245
246         /* some more paranoia, if the request was over-determined */
247         if (adm_ctx.mdev && adm_ctx.tconn &&
248             adm_ctx.mdev->tconn != adm_ctx.tconn) {
249                 pr_warning("request: minor=%u, resource=%s; but that minor belongs to connection %s\n",
250                                 adm_ctx.minor, adm_ctx.resource_name,
251                                 adm_ctx.mdev->tconn->name);
252                 drbd_msg_put_info("minor exists in different resource");
253                 return ERR_INVALID_REQUEST;
254         }
255         if (adm_ctx.mdev &&
256             adm_ctx.volume != VOLUME_UNSPECIFIED &&
257             adm_ctx.volume != adm_ctx.mdev->vnr) {
258                 pr_warning("request: minor=%u, volume=%u; but that minor is volume %u in %s\n",
259                                 adm_ctx.minor, adm_ctx.volume,
260                                 adm_ctx.mdev->vnr, adm_ctx.mdev->tconn->name);
261                 drbd_msg_put_info("minor exists as different volume");
262                 return ERR_INVALID_REQUEST;
263         }
264
265         return NO_ERROR;
266
267 fail:
268         nlmsg_free(adm_ctx.reply_skb);
269         adm_ctx.reply_skb = NULL;
270         return err;
271 }
272
273 static int drbd_adm_finish(struct genl_info *info, int retcode)
274 {
275         if (adm_ctx.tconn) {
276                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
277                 adm_ctx.tconn = NULL;
278         }
279
280         if (!adm_ctx.reply_skb)
281                 return -ENOMEM;
282
283         adm_ctx.reply_dh->ret_code = retcode;
284         drbd_adm_send_reply(adm_ctx.reply_skb, info);
285         return 0;
286 }
287
288 static void setup_khelper_env(struct drbd_tconn *tconn, char **envp)
289 {
290         char *afs;
291
292         /* FIXME: A future version will not allow this case. */
293         if (tconn->my_addr_len == 0 || tconn->peer_addr_len == 0)
294                 return;
295
296         switch (((struct sockaddr *)&tconn->peer_addr)->sa_family) {
297         case AF_INET6:
298                 afs = "ipv6";
299                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI6",
300                          &((struct sockaddr_in6 *)&tconn->peer_addr)->sin6_addr);
301                 break;
302         case AF_INET:
303                 afs = "ipv4";
304                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
305                          &((struct sockaddr_in *)&tconn->peer_addr)->sin_addr);
306                 break;
307         default:
308                 afs = "ssocks";
309                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
310                          &((struct sockaddr_in *)&tconn->peer_addr)->sin_addr);
311         }
312         snprintf(envp[3], 20, "DRBD_PEER_AF=%s", afs);
313 }
314
315 int drbd_khelper(struct drbd_conf *mdev, char *cmd)
316 {
317         char *envp[] = { "HOME=/",
318                         "TERM=linux",
319                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
320                          (char[20]) { }, /* address family */
321                          (char[60]) { }, /* address */
322                         NULL };
323         char mb[12];
324         char *argv[] = {usermode_helper, cmd, mb, NULL };
325         struct drbd_tconn *tconn = mdev->tconn;
326         struct sib_info sib;
327         int ret;
328
329         if (current == tconn->worker.task)
330                 set_bit(CALLBACK_PENDING, &tconn->flags);
331
332         snprintf(mb, 12, "minor-%d", mdev_to_minor(mdev));
333         setup_khelper_env(tconn, envp);
334
335         /* The helper may take some time.
336          * write out any unsynced meta data changes now */
337         drbd_md_sync(mdev);
338
339         dev_info(DEV, "helper command: %s %s %s\n", usermode_helper, cmd, mb);
340         sib.sib_reason = SIB_HELPER_PRE;
341         sib.helper_name = cmd;
342         drbd_bcast_event(mdev, &sib);
343         ret = call_usermodehelper(usermode_helper, argv, envp, UMH_WAIT_PROC);
344         if (ret)
345                 dev_warn(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
346                                 usermode_helper, cmd, mb,
347                                 (ret >> 8) & 0xff, ret);
348         else
349                 dev_info(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
350                                 usermode_helper, cmd, mb,
351                                 (ret >> 8) & 0xff, ret);
352         sib.sib_reason = SIB_HELPER_POST;
353         sib.helper_exit_code = ret;
354         drbd_bcast_event(mdev, &sib);
355
356         if (current == tconn->worker.task)
357                 clear_bit(CALLBACK_PENDING, &tconn->flags);
358
359         if (ret < 0) /* Ignore any ERRNOs we got. */
360                 ret = 0;
361
362         return ret;
363 }
364
365 int conn_khelper(struct drbd_tconn *tconn, char *cmd)
366 {
367         char *envp[] = { "HOME=/",
368                         "TERM=linux",
369                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
370                          (char[20]) { }, /* address family */
371                          (char[60]) { }, /* address */
372                         NULL };
373         char *argv[] = {usermode_helper, cmd, tconn->name, NULL };
374         int ret;
375
376         setup_khelper_env(tconn, envp);
377         conn_md_sync(tconn);
378
379         conn_info(tconn, "helper command: %s %s %s\n", usermode_helper, cmd, tconn->name);
380         /* TODO: conn_bcast_event() ?? */
381
382         ret = call_usermodehelper(usermode_helper, argv, envp, UMH_WAIT_PROC);
383         if (ret)
384                 conn_warn(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
385                           usermode_helper, cmd, tconn->name,
386                           (ret >> 8) & 0xff, ret);
387         else
388                 conn_info(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
389                           usermode_helper, cmd, tconn->name,
390                           (ret >> 8) & 0xff, ret);
391         /* TODO: conn_bcast_event() ?? */
392
393         if (ret < 0) /* Ignore any ERRNOs we got. */
394                 ret = 0;
395
396         return ret;
397 }
398
399 static enum drbd_fencing_p highest_fencing_policy(struct drbd_tconn *tconn)
400 {
401         enum drbd_fencing_p fp = FP_NOT_AVAIL;
402         struct drbd_conf *mdev;
403         int vnr;
404
405         rcu_read_lock();
406         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
407                 if (get_ldev_if_state(mdev, D_CONSISTENT)) {
408                         fp = max_t(enum drbd_fencing_p, fp,
409                                    rcu_dereference(mdev->ldev->disk_conf)->fencing);
410                         put_ldev(mdev);
411                 }
412         }
413         rcu_read_unlock();
414
415         return fp;
416 }
417
418 bool conn_try_outdate_peer(struct drbd_tconn *tconn)
419 {
420         union drbd_state mask = { };
421         union drbd_state val = { };
422         enum drbd_fencing_p fp;
423         char *ex_to_string;
424         int r;
425
426         if (tconn->cstate >= C_WF_REPORT_PARAMS) {
427                 conn_err(tconn, "Expected cstate < C_WF_REPORT_PARAMS\n");
428                 return false;
429         }
430
431         fp = highest_fencing_policy(tconn);
432         switch (fp) {
433         case FP_NOT_AVAIL:
434                 conn_warn(tconn, "Not fencing peer, I'm not even Consistent myself.\n");
435                 goto out;
436         case FP_DONT_CARE:
437                 return true;
438         default: ;
439         }
440
441         r = conn_khelper(tconn, "fence-peer");
442
443         switch ((r>>8) & 0xff) {
444         case 3: /* peer is inconsistent */
445                 ex_to_string = "peer is inconsistent or worse";
446                 mask.pdsk = D_MASK;
447                 val.pdsk = D_INCONSISTENT;
448                 break;
449         case 4: /* peer got outdated, or was already outdated */
450                 ex_to_string = "peer was fenced";
451                 mask.pdsk = D_MASK;
452                 val.pdsk = D_OUTDATED;
453                 break;
454         case 5: /* peer was down */
455                 if (conn_highest_disk(tconn) == D_UP_TO_DATE) {
456                         /* we will(have) create(d) a new UUID anyways... */
457                         ex_to_string = "peer is unreachable, assumed to be dead";
458                         mask.pdsk = D_MASK;
459                         val.pdsk = D_OUTDATED;
460                 } else {
461                         ex_to_string = "peer unreachable, doing nothing since disk != UpToDate";
462                 }
463                 break;
464         case 6: /* Peer is primary, voluntarily outdate myself.
465                  * This is useful when an unconnected R_SECONDARY is asked to
466                  * become R_PRIMARY, but finds the other peer being active. */
467                 ex_to_string = "peer is active";
468                 conn_warn(tconn, "Peer is primary, outdating myself.\n");
469                 mask.disk = D_MASK;
470                 val.disk = D_OUTDATED;
471                 break;
472         case 7:
473                 if (fp != FP_STONITH)
474                         conn_err(tconn, "fence-peer() = 7 && fencing != Stonith !!!\n");
475                 ex_to_string = "peer was stonithed";
476                 mask.pdsk = D_MASK;
477                 val.pdsk = D_OUTDATED;
478                 break;
479         default:
480                 /* The script is broken ... */
481                 conn_err(tconn, "fence-peer helper broken, returned %d\n", (r>>8)&0xff);
482                 return false; /* Eventually leave IO frozen */
483         }
484
485         conn_info(tconn, "fence-peer helper returned %d (%s)\n",
486                   (r>>8) & 0xff, ex_to_string);
487
488  out:
489
490         /* Not using
491            conn_request_state(tconn, mask, val, CS_VERBOSE);
492            here, because we might were able to re-establish the connection in the
493            meantime. */
494         spin_lock_irq(&tconn->req_lock);
495         if (tconn->cstate < C_WF_REPORT_PARAMS && !test_bit(STATE_SENT, &tconn->flags))
496                 _conn_request_state(tconn, mask, val, CS_VERBOSE);
497         spin_unlock_irq(&tconn->req_lock);
498
499         return conn_highest_pdsk(tconn) <= D_OUTDATED;
500 }
501
502 static int _try_outdate_peer_async(void *data)
503 {
504         struct drbd_tconn *tconn = (struct drbd_tconn *)data;
505
506         conn_try_outdate_peer(tconn);
507
508         kref_put(&tconn->kref, &conn_destroy);
509         return 0;
510 }
511
512 void conn_try_outdate_peer_async(struct drbd_tconn *tconn)
513 {
514         struct task_struct *opa;
515
516         kref_get(&tconn->kref);
517         opa = kthread_run(_try_outdate_peer_async, tconn, "drbd_async_h");
518         if (IS_ERR(opa)) {
519                 conn_err(tconn, "out of mem, failed to invoke fence-peer helper\n");
520                 kref_put(&tconn->kref, &conn_destroy);
521         }
522 }
523
524 enum drbd_state_rv
525 drbd_set_role(struct drbd_conf *mdev, enum drbd_role new_role, int force)
526 {
527         const int max_tries = 4;
528         enum drbd_state_rv rv = SS_UNKNOWN_ERROR;
529         struct net_conf *nc;
530         int try = 0;
531         int forced = 0;
532         union drbd_state mask, val;
533
534         if (new_role == R_PRIMARY)
535                 request_ping(mdev->tconn); /* Detect a dead peer ASAP */
536
537         mutex_lock(mdev->state_mutex);
538
539         mask.i = 0; mask.role = R_MASK;
540         val.i  = 0; val.role  = new_role;
541
542         while (try++ < max_tries) {
543                 rv = _drbd_request_state(mdev, mask, val, CS_WAIT_COMPLETE);
544
545                 /* in case we first succeeded to outdate,
546                  * but now suddenly could establish a connection */
547                 if (rv == SS_CW_FAILED_BY_PEER && mask.pdsk != 0) {
548                         val.pdsk = 0;
549                         mask.pdsk = 0;
550                         continue;
551                 }
552
553                 if (rv == SS_NO_UP_TO_DATE_DISK && force &&
554                     (mdev->state.disk < D_UP_TO_DATE &&
555                      mdev->state.disk >= D_INCONSISTENT)) {
556                         mask.disk = D_MASK;
557                         val.disk  = D_UP_TO_DATE;
558                         forced = 1;
559                         continue;
560                 }
561
562                 if (rv == SS_NO_UP_TO_DATE_DISK &&
563                     mdev->state.disk == D_CONSISTENT && mask.pdsk == 0) {
564                         D_ASSERT(mdev->state.pdsk == D_UNKNOWN);
565
566                         if (conn_try_outdate_peer(mdev->tconn)) {
567                                 val.disk = D_UP_TO_DATE;
568                                 mask.disk = D_MASK;
569                         }
570                         continue;
571                 }
572
573                 if (rv == SS_NOTHING_TO_DO)
574                         goto out;
575                 if (rv == SS_PRIMARY_NOP && mask.pdsk == 0) {
576                         if (!conn_try_outdate_peer(mdev->tconn) && force) {
577                                 dev_warn(DEV, "Forced into split brain situation!\n");
578                                 mask.pdsk = D_MASK;
579                                 val.pdsk  = D_OUTDATED;
580
581                         }
582                         continue;
583                 }
584                 if (rv == SS_TWO_PRIMARIES) {
585                         /* Maybe the peer is detected as dead very soon...
586                            retry at most once more in this case. */
587                         int timeo;
588                         rcu_read_lock();
589                         nc = rcu_dereference(mdev->tconn->net_conf);
590                         timeo = nc ? (nc->ping_timeo + 1) * HZ / 10 : 1;
591                         rcu_read_unlock();
592                         schedule_timeout_interruptible(timeo);
593                         if (try < max_tries)
594                                 try = max_tries - 1;
595                         continue;
596                 }
597                 if (rv < SS_SUCCESS) {
598                         rv = _drbd_request_state(mdev, mask, val,
599                                                 CS_VERBOSE + CS_WAIT_COMPLETE);
600                         if (rv < SS_SUCCESS)
601                                 goto out;
602                 }
603                 break;
604         }
605
606         if (rv < SS_SUCCESS)
607                 goto out;
608
609         if (forced)
610                 dev_warn(DEV, "Forced to consider local data as UpToDate!\n");
611
612         /* Wait until nothing is on the fly :) */
613         wait_event(mdev->misc_wait, atomic_read(&mdev->ap_pending_cnt) == 0);
614
615         /* FIXME also wait for all pending P_BARRIER_ACK? */
616
617         if (new_role == R_SECONDARY) {
618                 set_disk_ro(mdev->vdisk, true);
619                 if (get_ldev(mdev)) {
620                         mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
621                         put_ldev(mdev);
622                 }
623         } else {
624                 mutex_lock(&mdev->tconn->conf_update);
625                 nc = mdev->tconn->net_conf;
626                 if (nc)
627                         nc->discard_my_data = 0; /* without copy; single bit op is atomic */
628                 mutex_unlock(&mdev->tconn->conf_update);
629
630                 set_disk_ro(mdev->vdisk, false);
631                 if (get_ldev(mdev)) {
632                         if (((mdev->state.conn < C_CONNECTED ||
633                                mdev->state.pdsk <= D_FAILED)
634                               && mdev->ldev->md.uuid[UI_BITMAP] == 0) || forced)
635                                 drbd_uuid_new_current(mdev);
636
637                         mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
638                         put_ldev(mdev);
639                 }
640         }
641
642         /* writeout of activity log covered areas of the bitmap
643          * to stable storage done in after state change already */
644
645         if (mdev->state.conn >= C_WF_REPORT_PARAMS) {
646                 /* if this was forced, we should consider sync */
647                 if (forced)
648                         drbd_send_uuids(mdev);
649                 drbd_send_current_state(mdev);
650         }
651
652         drbd_md_sync(mdev);
653
654         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
655 out:
656         mutex_unlock(mdev->state_mutex);
657         return rv;
658 }
659
660 static const char *from_attrs_err_to_txt(int err)
661 {
662         return  err == -ENOMSG ? "required attribute missing" :
663                 err == -EOPNOTSUPP ? "unknown mandatory attribute" :
664                 err == -EEXIST ? "can not change invariant setting" :
665                 "invalid attribute value";
666 }
667
668 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info)
669 {
670         struct set_role_parms parms;
671         int err;
672         enum drbd_ret_code retcode;
673
674         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
675         if (!adm_ctx.reply_skb)
676                 return retcode;
677         if (retcode != NO_ERROR)
678                 goto out;
679
680         memset(&parms, 0, sizeof(parms));
681         if (info->attrs[DRBD_NLA_SET_ROLE_PARMS]) {
682                 err = set_role_parms_from_attrs(&parms, info);
683                 if (err) {
684                         retcode = ERR_MANDATORY_TAG;
685                         drbd_msg_put_info(from_attrs_err_to_txt(err));
686                         goto out;
687                 }
688         }
689
690         if (info->genlhdr->cmd == DRBD_ADM_PRIMARY)
691                 retcode = drbd_set_role(adm_ctx.mdev, R_PRIMARY, parms.assume_uptodate);
692         else
693                 retcode = drbd_set_role(adm_ctx.mdev, R_SECONDARY, 0);
694 out:
695         drbd_adm_finish(info, retcode);
696         return 0;
697 }
698
699 /* Initializes the md.*_offset members, so we are able to find
700  * the on disk meta data.
701  *
702  * We currently have two possible layouts:
703  * external:
704  *   |----------- md_size_sect ------------------|
705  *   [ 4k superblock ][ activity log ][  Bitmap  ]
706  *   | al_offset == 8 |
707  *   | bm_offset = al_offset + X      |
708  *  ==> bitmap sectors = md_size_sect - bm_offset
709  *
710  * internal:
711  *            |----------- md_size_sect ------------------|
712  * [data.....][  Bitmap  ][ activity log ][ 4k superblock ]
713  *                        | al_offset < 0 |
714  *            | bm_offset = al_offset - Y |
715  *  ==> bitmap sectors = Y = al_offset - bm_offset
716  *
717  *  Activity log size used to be fixed 32kB,
718  *  but is about to become configurable.
719  */
720 static void drbd_md_set_sector_offsets(struct drbd_conf *mdev,
721                                        struct drbd_backing_dev *bdev)
722 {
723         sector_t md_size_sect = 0;
724         unsigned int al_size_sect = MD_32kB_SECT;
725
726         bdev->md.md_offset = drbd_md_ss(bdev);
727
728         switch (bdev->md.meta_dev_idx) {
729         default:
730                 /* v07 style fixed size indexed meta data */
731                 bdev->md.md_size_sect = MD_128MB_SECT;
732                 bdev->md.al_offset = MD_4kB_SECT;
733                 bdev->md.bm_offset = MD_4kB_SECT + al_size_sect;
734                 break;
735         case DRBD_MD_INDEX_FLEX_EXT:
736                 /* just occupy the full device; unit: sectors */
737                 bdev->md.md_size_sect = drbd_get_capacity(bdev->md_bdev);
738                 bdev->md.al_offset = MD_4kB_SECT;
739                 bdev->md.bm_offset = MD_4kB_SECT + al_size_sect;
740                 break;
741         case DRBD_MD_INDEX_INTERNAL:
742         case DRBD_MD_INDEX_FLEX_INT:
743                 /* al size is still fixed */
744                 bdev->md.al_offset = -al_size_sect;
745                 /* we need (slightly less than) ~ this much bitmap sectors: */
746                 md_size_sect = drbd_get_capacity(bdev->backing_bdev);
747                 md_size_sect = ALIGN(md_size_sect, BM_SECT_PER_EXT);
748                 md_size_sect = BM_SECT_TO_EXT(md_size_sect);
749                 md_size_sect = ALIGN(md_size_sect, 8);
750
751                 /* plus the "drbd meta data super block",
752                  * and the activity log; */
753                 md_size_sect += MD_4kB_SECT + al_size_sect;
754
755                 bdev->md.md_size_sect = md_size_sect;
756                 /* bitmap offset is adjusted by 'super' block size */
757                 bdev->md.bm_offset   = -md_size_sect + MD_4kB_SECT;
758                 break;
759         }
760 }
761
762 /* input size is expected to be in KB */
763 char *ppsize(char *buf, unsigned long long size)
764 {
765         /* Needs 9 bytes at max including trailing NUL:
766          * -1ULL ==> "16384 EB" */
767         static char units[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
768         int base = 0;
769         while (size >= 10000 && base < sizeof(units)-1) {
770                 /* shift + round */
771                 size = (size >> 10) + !!(size & (1<<9));
772                 base++;
773         }
774         sprintf(buf, "%u %cB", (unsigned)size, units[base]);
775
776         return buf;
777 }
778
779 /* there is still a theoretical deadlock when called from receiver
780  * on an D_INCONSISTENT R_PRIMARY:
781  *  remote READ does inc_ap_bio, receiver would need to receive answer
782  *  packet from remote to dec_ap_bio again.
783  *  receiver receive_sizes(), comes here,
784  *  waits for ap_bio_cnt == 0. -> deadlock.
785  * but this cannot happen, actually, because:
786  *  R_PRIMARY D_INCONSISTENT, and peer's disk is unreachable
787  *  (not connected, or bad/no disk on peer):
788  *  see drbd_fail_request_early, ap_bio_cnt is zero.
789  *  R_PRIMARY D_INCONSISTENT, and C_SYNC_TARGET:
790  *  peer may not initiate a resize.
791  */
792 /* Note these are not to be confused with
793  * drbd_adm_suspend_io/drbd_adm_resume_io,
794  * which are (sub) state changes triggered by admin (drbdsetup),
795  * and can be long lived.
796  * This changes an mdev->flag, is triggered by drbd internals,
797  * and should be short-lived. */
798 void drbd_suspend_io(struct drbd_conf *mdev)
799 {
800         set_bit(SUSPEND_IO, &mdev->flags);
801         if (drbd_suspended(mdev))
802                 return;
803         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_bio_cnt));
804 }
805
806 void drbd_resume_io(struct drbd_conf *mdev)
807 {
808         clear_bit(SUSPEND_IO, &mdev->flags);
809         wake_up(&mdev->misc_wait);
810 }
811
812 /**
813  * drbd_determine_dev_size() -  Sets the right device size obeying all constraints
814  * @mdev:       DRBD device.
815  *
816  * Returns 0 on success, negative return values indicate errors.
817  * You should call drbd_md_sync() after calling this function.
818  */
819 enum determine_dev_size drbd_determine_dev_size(struct drbd_conf *mdev, enum dds_flags flags) __must_hold(local)
820 {
821         sector_t prev_first_sect, prev_size; /* previous meta location */
822         sector_t la_size, u_size;
823         sector_t size;
824         char ppb[10];
825
826         int md_moved, la_size_changed;
827         enum determine_dev_size rv = unchanged;
828
829         /* race:
830          * application request passes inc_ap_bio,
831          * but then cannot get an AL-reference.
832          * this function later may wait on ap_bio_cnt == 0. -> deadlock.
833          *
834          * to avoid that:
835          * Suspend IO right here.
836          * still lock the act_log to not trigger ASSERTs there.
837          */
838         drbd_suspend_io(mdev);
839
840         /* no wait necessary anymore, actually we could assert that */
841         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
842
843         prev_first_sect = drbd_md_first_sector(mdev->ldev);
844         prev_size = mdev->ldev->md.md_size_sect;
845         la_size = mdev->ldev->md.la_size_sect;
846
847         /* TODO: should only be some assert here, not (re)init... */
848         drbd_md_set_sector_offsets(mdev, mdev->ldev);
849
850         rcu_read_lock();
851         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
852         rcu_read_unlock();
853         size = drbd_new_dev_size(mdev, mdev->ldev, u_size, flags & DDSF_FORCED);
854
855         if (drbd_get_capacity(mdev->this_bdev) != size ||
856             drbd_bm_capacity(mdev) != size) {
857                 int err;
858                 err = drbd_bm_resize(mdev, size, !(flags & DDSF_NO_RESYNC));
859                 if (unlikely(err)) {
860                         /* currently there is only one error: ENOMEM! */
861                         size = drbd_bm_capacity(mdev)>>1;
862                         if (size == 0) {
863                                 dev_err(DEV, "OUT OF MEMORY! "
864                                     "Could not allocate bitmap!\n");
865                         } else {
866                                 dev_err(DEV, "BM resizing failed. "
867                                     "Leaving size unchanged at size = %lu KB\n",
868                                     (unsigned long)size);
869                         }
870                         rv = dev_size_error;
871                 }
872                 /* racy, see comments above. */
873                 drbd_set_my_capacity(mdev, size);
874                 mdev->ldev->md.la_size_sect = size;
875                 dev_info(DEV, "size = %s (%llu KB)\n", ppsize(ppb, size>>1),
876                      (unsigned long long)size>>1);
877         }
878         if (rv == dev_size_error)
879                 goto out;
880
881         la_size_changed = (la_size != mdev->ldev->md.la_size_sect);
882
883         md_moved = prev_first_sect != drbd_md_first_sector(mdev->ldev)
884                 || prev_size       != mdev->ldev->md.md_size_sect;
885
886         if (la_size_changed || md_moved) {
887                 int err;
888
889                 drbd_al_shrink(mdev); /* All extents inactive. */
890                 dev_info(DEV, "Writing the whole bitmap, %s\n",
891                          la_size_changed && md_moved ? "size changed and md moved" :
892                          la_size_changed ? "size changed" : "md moved");
893                 /* next line implicitly does drbd_suspend_io()+drbd_resume_io() */
894                 err = drbd_bitmap_io(mdev, md_moved ? &drbd_bm_write_all : &drbd_bm_write,
895                                      "size changed", BM_LOCKED_MASK);
896                 if (err) {
897                         rv = dev_size_error;
898                         goto out;
899                 }
900                 drbd_md_mark_dirty(mdev);
901         }
902
903         if (size > la_size)
904                 rv = grew;
905         if (size < la_size)
906                 rv = shrunk;
907 out:
908         lc_unlock(mdev->act_log);
909         wake_up(&mdev->al_wait);
910         drbd_resume_io(mdev);
911
912         return rv;
913 }
914
915 sector_t
916 drbd_new_dev_size(struct drbd_conf *mdev, struct drbd_backing_dev *bdev,
917                   sector_t u_size, int assume_peer_has_space)
918 {
919         sector_t p_size = mdev->p_size;   /* partner's disk size. */
920         sector_t la_size = bdev->md.la_size_sect; /* last agreed size. */
921         sector_t m_size; /* my size */
922         sector_t size = 0;
923
924         m_size = drbd_get_max_capacity(bdev);
925
926         if (mdev->state.conn < C_CONNECTED && assume_peer_has_space) {
927                 dev_warn(DEV, "Resize while not connected was forced by the user!\n");
928                 p_size = m_size;
929         }
930
931         if (p_size && m_size) {
932                 size = min_t(sector_t, p_size, m_size);
933         } else {
934                 if (la_size) {
935                         size = la_size;
936                         if (m_size && m_size < size)
937                                 size = m_size;
938                         if (p_size && p_size < size)
939                                 size = p_size;
940                 } else {
941                         if (m_size)
942                                 size = m_size;
943                         if (p_size)
944                                 size = p_size;
945                 }
946         }
947
948         if (size == 0)
949                 dev_err(DEV, "Both nodes diskless!\n");
950
951         if (u_size) {
952                 if (u_size > size)
953                         dev_err(DEV, "Requested disk size is too big (%lu > %lu)\n",
954                             (unsigned long)u_size>>1, (unsigned long)size>>1);
955                 else
956                         size = u_size;
957         }
958
959         return size;
960 }
961
962 /**
963  * drbd_check_al_size() - Ensures that the AL is of the right size
964  * @mdev:       DRBD device.
965  *
966  * Returns -EBUSY if current al lru is still used, -ENOMEM when allocation
967  * failed, and 0 on success. You should call drbd_md_sync() after you called
968  * this function.
969  */
970 static int drbd_check_al_size(struct drbd_conf *mdev, struct disk_conf *dc)
971 {
972         struct lru_cache *n, *t;
973         struct lc_element *e;
974         unsigned int in_use;
975         int i;
976
977         if (mdev->act_log &&
978             mdev->act_log->nr_elements == dc->al_extents)
979                 return 0;
980
981         in_use = 0;
982         t = mdev->act_log;
983         n = lc_create("act_log", drbd_al_ext_cache, AL_UPDATES_PER_TRANSACTION,
984                 dc->al_extents, sizeof(struct lc_element), 0);
985
986         if (n == NULL) {
987                 dev_err(DEV, "Cannot allocate act_log lru!\n");
988                 return -ENOMEM;
989         }
990         spin_lock_irq(&mdev->al_lock);
991         if (t) {
992                 for (i = 0; i < t->nr_elements; i++) {
993                         e = lc_element_by_index(t, i);
994                         if (e->refcnt)
995                                 dev_err(DEV, "refcnt(%d)==%d\n",
996                                     e->lc_number, e->refcnt);
997                         in_use += e->refcnt;
998                 }
999         }
1000         if (!in_use)
1001                 mdev->act_log = n;
1002         spin_unlock_irq(&mdev->al_lock);
1003         if (in_use) {
1004                 dev_err(DEV, "Activity log still in use!\n");
1005                 lc_destroy(n);
1006                 return -EBUSY;
1007         } else {
1008                 if (t)
1009                         lc_destroy(t);
1010         }
1011         drbd_md_mark_dirty(mdev); /* we changed mdev->act_log->nr_elemens */
1012         return 0;
1013 }
1014
1015 static void drbd_setup_queue_param(struct drbd_conf *mdev, unsigned int max_bio_size)
1016 {
1017         struct request_queue * const q = mdev->rq_queue;
1018         unsigned int max_hw_sectors = max_bio_size >> 9;
1019         unsigned int max_segments = 0;
1020
1021         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1022                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
1023
1024                 max_hw_sectors = min(queue_max_hw_sectors(b), max_bio_size >> 9);
1025                 rcu_read_lock();
1026                 max_segments = rcu_dereference(mdev->ldev->disk_conf)->max_bio_bvecs;
1027                 rcu_read_unlock();
1028                 put_ldev(mdev);
1029         }
1030
1031         blk_queue_logical_block_size(q, 512);
1032         blk_queue_max_hw_sectors(q, max_hw_sectors);
1033         /* This is the workaround for "bio would need to, but cannot, be split" */
1034         blk_queue_max_segments(q, max_segments ? max_segments : BLK_MAX_SEGMENTS);
1035         blk_queue_segment_boundary(q, PAGE_CACHE_SIZE-1);
1036
1037         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1038                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
1039
1040                 blk_queue_stack_limits(q, b);
1041
1042                 if (q->backing_dev_info.ra_pages != b->backing_dev_info.ra_pages) {
1043                         dev_info(DEV, "Adjusting my ra_pages to backing device's (%lu -> %lu)\n",
1044                                  q->backing_dev_info.ra_pages,
1045                                  b->backing_dev_info.ra_pages);
1046                         q->backing_dev_info.ra_pages = b->backing_dev_info.ra_pages;
1047                 }
1048                 put_ldev(mdev);
1049         }
1050 }
1051
1052 void drbd_reconsider_max_bio_size(struct drbd_conf *mdev)
1053 {
1054         unsigned int now, new, local, peer;
1055
1056         now = queue_max_hw_sectors(mdev->rq_queue) << 9;
1057         local = mdev->local_max_bio_size; /* Eventually last known value, from volatile memory */
1058         peer = mdev->peer_max_bio_size; /* Eventually last known value, from meta data */
1059
1060         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1061                 local = queue_max_hw_sectors(mdev->ldev->backing_bdev->bd_disk->queue) << 9;
1062                 mdev->local_max_bio_size = local;
1063                 put_ldev(mdev);
1064         }
1065         local = min(local, DRBD_MAX_BIO_SIZE);
1066
1067         /* We may ignore peer limits if the peer is modern enough.
1068            Because new from 8.3.8 onwards the peer can use multiple
1069            BIOs for a single peer_request */
1070         if (mdev->state.conn >= C_CONNECTED) {
1071                 if (mdev->tconn->agreed_pro_version < 94)
1072                         peer = min( mdev->peer_max_bio_size, DRBD_MAX_SIZE_H80_PACKET);
1073                         /* Correct old drbd (up to 8.3.7) if it believes it can do more than 32KiB */
1074                 else if (mdev->tconn->agreed_pro_version == 94)
1075                         peer = DRBD_MAX_SIZE_H80_PACKET;
1076                 else if (mdev->tconn->agreed_pro_version < 100)
1077                         peer = DRBD_MAX_BIO_SIZE_P95;  /* drbd 8.3.8 onwards, before 8.4.0 */
1078                 else
1079                         peer = DRBD_MAX_BIO_SIZE;
1080         }
1081
1082         new = min(local, peer);
1083
1084         if (mdev->state.role == R_PRIMARY && new < now)
1085                 dev_err(DEV, "ASSERT FAILED new < now; (%u < %u)\n", new, now);
1086
1087         if (new != now)
1088                 dev_info(DEV, "max BIO size = %u\n", new);
1089
1090         drbd_setup_queue_param(mdev, new);
1091 }
1092
1093 /* Starts the worker thread */
1094 static void conn_reconfig_start(struct drbd_tconn *tconn)
1095 {
1096         drbd_thread_start(&tconn->worker);
1097         conn_flush_workqueue(tconn);
1098 }
1099
1100 /* if still unconfigured, stops worker again. */
1101 static void conn_reconfig_done(struct drbd_tconn *tconn)
1102 {
1103         bool stop_threads;
1104         spin_lock_irq(&tconn->req_lock);
1105         stop_threads = conn_all_vols_unconf(tconn) &&
1106                 tconn->cstate == C_STANDALONE;
1107         spin_unlock_irq(&tconn->req_lock);
1108         if (stop_threads) {
1109                 /* asender is implicitly stopped by receiver
1110                  * in conn_disconnect() */
1111                 drbd_thread_stop(&tconn->receiver);
1112                 drbd_thread_stop(&tconn->worker);
1113         }
1114 }
1115
1116 /* Make sure IO is suspended before calling this function(). */
1117 static void drbd_suspend_al(struct drbd_conf *mdev)
1118 {
1119         int s = 0;
1120
1121         if (!lc_try_lock(mdev->act_log)) {
1122                 dev_warn(DEV, "Failed to lock al in drbd_suspend_al()\n");
1123                 return;
1124         }
1125
1126         drbd_al_shrink(mdev);
1127         spin_lock_irq(&mdev->tconn->req_lock);
1128         if (mdev->state.conn < C_CONNECTED)
1129                 s = !test_and_set_bit(AL_SUSPENDED, &mdev->flags);
1130         spin_unlock_irq(&mdev->tconn->req_lock);
1131         lc_unlock(mdev->act_log);
1132
1133         if (s)
1134                 dev_info(DEV, "Suspended AL updates\n");
1135 }
1136
1137
1138 static bool should_set_defaults(struct genl_info *info)
1139 {
1140         unsigned flags = ((struct drbd_genlmsghdr*)info->userhdr)->flags;
1141         return 0 != (flags & DRBD_GENL_F_SET_DEFAULTS);
1142 }
1143
1144 static void enforce_disk_conf_limits(struct disk_conf *dc)
1145 {
1146         if (dc->al_extents < DRBD_AL_EXTENTS_MIN)
1147                 dc->al_extents = DRBD_AL_EXTENTS_MIN;
1148         if (dc->al_extents > DRBD_AL_EXTENTS_MAX)
1149                 dc->al_extents = DRBD_AL_EXTENTS_MAX;
1150
1151         if (dc->c_plan_ahead > DRBD_C_PLAN_AHEAD_MAX)
1152                 dc->c_plan_ahead = DRBD_C_PLAN_AHEAD_MAX;
1153 }
1154
1155 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info)
1156 {
1157         enum drbd_ret_code retcode;
1158         struct drbd_conf *mdev;
1159         struct disk_conf *new_disk_conf, *old_disk_conf;
1160         struct fifo_buffer *old_plan = NULL, *new_plan = NULL;
1161         int err, fifo_size;
1162
1163         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1164         if (!adm_ctx.reply_skb)
1165                 return retcode;
1166         if (retcode != NO_ERROR)
1167                 goto out;
1168
1169         mdev = adm_ctx.mdev;
1170
1171         /* we also need a disk
1172          * to change the options on */
1173         if (!get_ldev(mdev)) {
1174                 retcode = ERR_NO_DISK;
1175                 goto out;
1176         }
1177
1178         new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
1179         if (!new_disk_conf) {
1180                 retcode = ERR_NOMEM;
1181                 goto fail;
1182         }
1183
1184         mutex_lock(&mdev->tconn->conf_update);
1185         old_disk_conf = mdev->ldev->disk_conf;
1186         *new_disk_conf = *old_disk_conf;
1187         if (should_set_defaults(info))
1188                 set_disk_conf_defaults(new_disk_conf);
1189
1190         err = disk_conf_from_attrs_for_change(new_disk_conf, info);
1191         if (err && err != -ENOMSG) {
1192                 retcode = ERR_MANDATORY_TAG;
1193                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1194         }
1195
1196         if (!expect(new_disk_conf->resync_rate >= 1))
1197                 new_disk_conf->resync_rate = 1;
1198
1199         enforce_disk_conf_limits(new_disk_conf);
1200
1201         fifo_size = (new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ;
1202         if (fifo_size != mdev->rs_plan_s->size) {
1203                 new_plan = fifo_alloc(fifo_size);
1204                 if (!new_plan) {
1205                         dev_err(DEV, "kmalloc of fifo_buffer failed");
1206                         retcode = ERR_NOMEM;
1207                         goto fail_unlock;
1208                 }
1209         }
1210
1211         drbd_suspend_io(mdev);
1212         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
1213         drbd_al_shrink(mdev);
1214         err = drbd_check_al_size(mdev, new_disk_conf);
1215         lc_unlock(mdev->act_log);
1216         wake_up(&mdev->al_wait);
1217         drbd_resume_io(mdev);
1218
1219         if (err) {
1220                 retcode = ERR_NOMEM;
1221                 goto fail_unlock;
1222         }
1223
1224         write_lock_irq(&global_state_lock);
1225         retcode = drbd_resync_after_valid(mdev, new_disk_conf->resync_after);
1226         if (retcode == NO_ERROR) {
1227                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
1228                 drbd_resync_after_changed(mdev);
1229         }
1230         write_unlock_irq(&global_state_lock);
1231
1232         if (retcode != NO_ERROR)
1233                 goto fail_unlock;
1234
1235         if (new_plan) {
1236                 old_plan = mdev->rs_plan_s;
1237                 rcu_assign_pointer(mdev->rs_plan_s, new_plan);
1238         }
1239
1240         mutex_unlock(&mdev->tconn->conf_update);
1241
1242         if (new_disk_conf->al_updates)
1243                 mdev->ldev->md.flags &= ~MDF_AL_DISABLED;
1244         else
1245                 mdev->ldev->md.flags |= MDF_AL_DISABLED;
1246
1247         if (new_disk_conf->md_flushes)
1248                 clear_bit(MD_NO_FUA, &mdev->flags);
1249         else
1250                 set_bit(MD_NO_FUA, &mdev->flags);
1251
1252         drbd_bump_write_ordering(mdev->tconn, WO_bdev_flush);
1253
1254         drbd_md_sync(mdev);
1255
1256         if (mdev->state.conn >= C_CONNECTED)
1257                 drbd_send_sync_param(mdev);
1258
1259         synchronize_rcu();
1260         kfree(old_disk_conf);
1261         kfree(old_plan);
1262         mod_timer(&mdev->request_timer, jiffies + HZ);
1263         goto success;
1264
1265 fail_unlock:
1266         mutex_unlock(&mdev->tconn->conf_update);
1267  fail:
1268         kfree(new_disk_conf);
1269         kfree(new_plan);
1270 success:
1271         put_ldev(mdev);
1272  out:
1273         drbd_adm_finish(info, retcode);
1274         return 0;
1275 }
1276
1277 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info)
1278 {
1279         struct drbd_conf *mdev;
1280         int err;
1281         enum drbd_ret_code retcode;
1282         enum determine_dev_size dd;
1283         sector_t max_possible_sectors;
1284         sector_t min_md_device_sectors;
1285         struct drbd_backing_dev *nbc = NULL; /* new_backing_conf */
1286         struct disk_conf *new_disk_conf = NULL;
1287         struct block_device *bdev;
1288         struct lru_cache *resync_lru = NULL;
1289         struct fifo_buffer *new_plan = NULL;
1290         union drbd_state ns, os;
1291         enum drbd_state_rv rv;
1292         struct net_conf *nc;
1293
1294         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1295         if (!adm_ctx.reply_skb)
1296                 return retcode;
1297         if (retcode != NO_ERROR)
1298                 goto finish;
1299
1300         mdev = adm_ctx.mdev;
1301         conn_reconfig_start(mdev->tconn);
1302
1303         /* if you want to reconfigure, please tear down first */
1304         if (mdev->state.disk > D_DISKLESS) {
1305                 retcode = ERR_DISK_CONFIGURED;
1306                 goto fail;
1307         }
1308         /* It may just now have detached because of IO error.  Make sure
1309          * drbd_ldev_destroy is done already, we may end up here very fast,
1310          * e.g. if someone calls attach from the on-io-error handler,
1311          * to realize a "hot spare" feature (not that I'd recommend that) */
1312         wait_event(mdev->misc_wait, !atomic_read(&mdev->local_cnt));
1313
1314         /* make sure there is no leftover from previous force-detach attempts */
1315         clear_bit(FORCE_DETACH, &mdev->flags);
1316         clear_bit(WAS_IO_ERROR, &mdev->flags);
1317         clear_bit(WAS_READ_ERROR, &mdev->flags);
1318
1319         /* and no leftover from previously aborted resync or verify, either */
1320         mdev->rs_total = 0;
1321         mdev->rs_failed = 0;
1322         atomic_set(&mdev->rs_pending_cnt, 0);
1323
1324         /* allocation not in the IO path, drbdsetup context */
1325         nbc = kzalloc(sizeof(struct drbd_backing_dev), GFP_KERNEL);
1326         if (!nbc) {
1327                 retcode = ERR_NOMEM;
1328                 goto fail;
1329         }
1330         spin_lock_init(&nbc->md.uuid_lock);
1331
1332         new_disk_conf = kzalloc(sizeof(struct disk_conf), GFP_KERNEL);
1333         if (!new_disk_conf) {
1334                 retcode = ERR_NOMEM;
1335                 goto fail;
1336         }
1337         nbc->disk_conf = new_disk_conf;
1338
1339         set_disk_conf_defaults(new_disk_conf);
1340         err = disk_conf_from_attrs(new_disk_conf, info);
1341         if (err) {
1342                 retcode = ERR_MANDATORY_TAG;
1343                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1344                 goto fail;
1345         }
1346
1347         enforce_disk_conf_limits(new_disk_conf);
1348
1349         new_plan = fifo_alloc((new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ);
1350         if (!new_plan) {
1351                 retcode = ERR_NOMEM;
1352                 goto fail;
1353         }
1354
1355         if (new_disk_conf->meta_dev_idx < DRBD_MD_INDEX_FLEX_INT) {
1356                 retcode = ERR_MD_IDX_INVALID;
1357                 goto fail;
1358         }
1359
1360         rcu_read_lock();
1361         nc = rcu_dereference(mdev->tconn->net_conf);
1362         if (nc) {
1363                 if (new_disk_conf->fencing == FP_STONITH && nc->wire_protocol == DRBD_PROT_A) {
1364                         rcu_read_unlock();
1365                         retcode = ERR_STONITH_AND_PROT_A;
1366                         goto fail;
1367                 }
1368         }
1369         rcu_read_unlock();
1370
1371         bdev = blkdev_get_by_path(new_disk_conf->backing_dev,
1372                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL, mdev);
1373         if (IS_ERR(bdev)) {
1374                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->backing_dev,
1375                         PTR_ERR(bdev));
1376                 retcode = ERR_OPEN_DISK;
1377                 goto fail;
1378         }
1379         nbc->backing_bdev = bdev;
1380
1381         /*
1382          * meta_dev_idx >= 0: external fixed size, possibly multiple
1383          * drbd sharing one meta device.  TODO in that case, paranoia
1384          * check that [md_bdev, meta_dev_idx] is not yet used by some
1385          * other drbd minor!  (if you use drbd.conf + drbdadm, that
1386          * should check it for you already; but if you don't, or
1387          * someone fooled it, we need to double check here)
1388          */
1389         bdev = blkdev_get_by_path(new_disk_conf->meta_dev,
1390                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL,
1391                                   (new_disk_conf->meta_dev_idx < 0) ?
1392                                   (void *)mdev : (void *)drbd_m_holder);
1393         if (IS_ERR(bdev)) {
1394                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->meta_dev,
1395                         PTR_ERR(bdev));
1396                 retcode = ERR_OPEN_MD_DISK;
1397                 goto fail;
1398         }
1399         nbc->md_bdev = bdev;
1400
1401         if ((nbc->backing_bdev == nbc->md_bdev) !=
1402             (new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_INTERNAL ||
1403              new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_FLEX_INT)) {
1404                 retcode = ERR_MD_IDX_INVALID;
1405                 goto fail;
1406         }
1407
1408         resync_lru = lc_create("resync", drbd_bm_ext_cache,
1409                         1, 61, sizeof(struct bm_extent),
1410                         offsetof(struct bm_extent, lce));
1411         if (!resync_lru) {
1412                 retcode = ERR_NOMEM;
1413                 goto fail;
1414         }
1415
1416         /* RT - for drbd_get_max_capacity() DRBD_MD_INDEX_FLEX_INT */
1417         drbd_md_set_sector_offsets(mdev, nbc);
1418
1419         if (drbd_get_max_capacity(nbc) < new_disk_conf->disk_size) {
1420                 dev_err(DEV, "max capacity %llu smaller than disk size %llu\n",
1421                         (unsigned long long) drbd_get_max_capacity(nbc),
1422                         (unsigned long long) new_disk_conf->disk_size);
1423                 retcode = ERR_DISK_TOO_SMALL;
1424                 goto fail;
1425         }
1426
1427         if (new_disk_conf->meta_dev_idx < 0) {
1428                 max_possible_sectors = DRBD_MAX_SECTORS_FLEX;
1429                 /* at least one MB, otherwise it does not make sense */
1430                 min_md_device_sectors = (2<<10);
1431         } else {
1432                 max_possible_sectors = DRBD_MAX_SECTORS;
1433                 min_md_device_sectors = MD_128MB_SECT * (new_disk_conf->meta_dev_idx + 1);
1434         }
1435
1436         if (drbd_get_capacity(nbc->md_bdev) < min_md_device_sectors) {
1437                 retcode = ERR_MD_DISK_TOO_SMALL;
1438                 dev_warn(DEV, "refusing attach: md-device too small, "
1439                      "at least %llu sectors needed for this meta-disk type\n",
1440                      (unsigned long long) min_md_device_sectors);
1441                 goto fail;
1442         }
1443
1444         /* Make sure the new disk is big enough
1445          * (we may currently be R_PRIMARY with no local disk...) */
1446         if (drbd_get_max_capacity(nbc) <
1447             drbd_get_capacity(mdev->this_bdev)) {
1448                 retcode = ERR_DISK_TOO_SMALL;
1449                 goto fail;
1450         }
1451
1452         nbc->known_size = drbd_get_capacity(nbc->backing_bdev);
1453
1454         if (nbc->known_size > max_possible_sectors) {
1455                 dev_warn(DEV, "==> truncating very big lower level device "
1456                         "to currently maximum possible %llu sectors <==\n",
1457                         (unsigned long long) max_possible_sectors);
1458                 if (new_disk_conf->meta_dev_idx >= 0)
1459                         dev_warn(DEV, "==>> using internal or flexible "
1460                                       "meta data may help <<==\n");
1461         }
1462
1463         drbd_suspend_io(mdev);
1464         /* also wait for the last barrier ack. */
1465         /* FIXME see also https://daiquiri.linbit/cgi-bin/bugzilla/show_bug.cgi?id=171
1466          * We need a way to either ignore barrier acks for barriers sent before a device
1467          * was attached, or a way to wait for all pending barrier acks to come in.
1468          * As barriers are counted per resource,
1469          * we'd need to suspend io on all devices of a resource.
1470          */
1471         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_pending_cnt) || drbd_suspended(mdev));
1472         /* and for any other previously queued work */
1473         drbd_flush_workqueue(mdev);
1474
1475         rv = _drbd_request_state(mdev, NS(disk, D_ATTACHING), CS_VERBOSE);
1476         retcode = rv;  /* FIXME: Type mismatch. */
1477         drbd_resume_io(mdev);
1478         if (rv < SS_SUCCESS)
1479                 goto fail;
1480
1481         if (!get_ldev_if_state(mdev, D_ATTACHING))
1482                 goto force_diskless;
1483
1484         drbd_md_set_sector_offsets(mdev, nbc);
1485
1486         if (!mdev->bitmap) {
1487                 if (drbd_bm_init(mdev)) {
1488                         retcode = ERR_NOMEM;
1489                         goto force_diskless_dec;
1490                 }
1491         }
1492
1493         retcode = drbd_md_read(mdev, nbc);
1494         if (retcode != NO_ERROR)
1495                 goto force_diskless_dec;
1496
1497         if (mdev->state.conn < C_CONNECTED &&
1498             mdev->state.role == R_PRIMARY &&
1499             (mdev->ed_uuid & ~((u64)1)) != (nbc->md.uuid[UI_CURRENT] & ~((u64)1))) {
1500                 dev_err(DEV, "Can only attach to data with current UUID=%016llX\n",
1501                     (unsigned long long)mdev->ed_uuid);
1502                 retcode = ERR_DATA_NOT_CURRENT;
1503                 goto force_diskless_dec;
1504         }
1505
1506         /* Since we are diskless, fix the activity log first... */
1507         if (drbd_check_al_size(mdev, new_disk_conf)) {
1508                 retcode = ERR_NOMEM;
1509                 goto force_diskless_dec;
1510         }
1511
1512         /* Prevent shrinking of consistent devices ! */
1513         if (drbd_md_test_flag(nbc, MDF_CONSISTENT) &&
1514             drbd_new_dev_size(mdev, nbc, nbc->disk_conf->disk_size, 0) < nbc->md.la_size_sect) {
1515                 dev_warn(DEV, "refusing to truncate a consistent device\n");
1516                 retcode = ERR_DISK_TOO_SMALL;
1517                 goto force_diskless_dec;
1518         }
1519
1520         /* Reset the "barriers don't work" bits here, then force meta data to
1521          * be written, to ensure we determine if barriers are supported. */
1522         if (new_disk_conf->md_flushes)
1523                 clear_bit(MD_NO_FUA, &mdev->flags);
1524         else
1525                 set_bit(MD_NO_FUA, &mdev->flags);
1526
1527         /* Point of no return reached.
1528          * Devices and memory are no longer released by error cleanup below.
1529          * now mdev takes over responsibility, and the state engine should
1530          * clean it up somewhere.  */
1531         D_ASSERT(mdev->ldev == NULL);
1532         mdev->ldev = nbc;
1533         mdev->resync = resync_lru;
1534         mdev->rs_plan_s = new_plan;
1535         nbc = NULL;
1536         resync_lru = NULL;
1537         new_disk_conf = NULL;
1538         new_plan = NULL;
1539
1540         drbd_bump_write_ordering(mdev->tconn, WO_bdev_flush);
1541
1542         if (drbd_md_test_flag(mdev->ldev, MDF_CRASHED_PRIMARY))
1543                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1544         else
1545                 clear_bit(CRASHED_PRIMARY, &mdev->flags);
1546
1547         if (drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1548             !(mdev->state.role == R_PRIMARY && mdev->tconn->susp_nod))
1549                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1550
1551         mdev->send_cnt = 0;
1552         mdev->recv_cnt = 0;
1553         mdev->read_cnt = 0;
1554         mdev->writ_cnt = 0;
1555
1556         drbd_reconsider_max_bio_size(mdev);
1557
1558         /* If I am currently not R_PRIMARY,
1559          * but meta data primary indicator is set,
1560          * I just now recover from a hard crash,
1561          * and have been R_PRIMARY before that crash.
1562          *
1563          * Now, if I had no connection before that crash
1564          * (have been degraded R_PRIMARY), chances are that
1565          * I won't find my peer now either.
1566          *
1567          * In that case, and _only_ in that case,
1568          * we use the degr-wfc-timeout instead of the default,
1569          * so we can automatically recover from a crash of a
1570          * degraded but active "cluster" after a certain timeout.
1571          */
1572         clear_bit(USE_DEGR_WFC_T, &mdev->flags);
1573         if (mdev->state.role != R_PRIMARY &&
1574              drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1575             !drbd_md_test_flag(mdev->ldev, MDF_CONNECTED_IND))
1576                 set_bit(USE_DEGR_WFC_T, &mdev->flags);
1577
1578         dd = drbd_determine_dev_size(mdev, 0);
1579         if (dd == dev_size_error) {
1580                 retcode = ERR_NOMEM_BITMAP;
1581                 goto force_diskless_dec;
1582         } else if (dd == grew)
1583                 set_bit(RESYNC_AFTER_NEG, &mdev->flags);
1584
1585         if (drbd_md_test_flag(mdev->ldev, MDF_FULL_SYNC) ||
1586             (test_bit(CRASHED_PRIMARY, &mdev->flags) &&
1587              drbd_md_test_flag(mdev->ldev, MDF_AL_DISABLED))) {
1588                 dev_info(DEV, "Assuming that all blocks are out of sync "
1589                      "(aka FullSync)\n");
1590                 if (drbd_bitmap_io(mdev, &drbd_bmio_set_n_write,
1591                         "set_n_write from attaching", BM_LOCKED_MASK)) {
1592                         retcode = ERR_IO_MD_DISK;
1593                         goto force_diskless_dec;
1594                 }
1595         } else {
1596                 if (drbd_bitmap_io(mdev, &drbd_bm_read,
1597                         "read from attaching", BM_LOCKED_MASK)) {
1598                         retcode = ERR_IO_MD_DISK;
1599                         goto force_diskless_dec;
1600                 }
1601         }
1602
1603         if (_drbd_bm_total_weight(mdev) == drbd_bm_bits(mdev))
1604                 drbd_suspend_al(mdev); /* IO is still suspended here... */
1605
1606         spin_lock_irq(&mdev->tconn->req_lock);
1607         os = drbd_read_state(mdev);
1608         ns = os;
1609         /* If MDF_CONSISTENT is not set go into inconsistent state,
1610            otherwise investigate MDF_WasUpToDate...
1611            If MDF_WAS_UP_TO_DATE is not set go into D_OUTDATED disk state,
1612            otherwise into D_CONSISTENT state.
1613         */
1614         if (drbd_md_test_flag(mdev->ldev, MDF_CONSISTENT)) {
1615                 if (drbd_md_test_flag(mdev->ldev, MDF_WAS_UP_TO_DATE))
1616                         ns.disk = D_CONSISTENT;
1617                 else
1618                         ns.disk = D_OUTDATED;
1619         } else {
1620                 ns.disk = D_INCONSISTENT;
1621         }
1622
1623         if (drbd_md_test_flag(mdev->ldev, MDF_PEER_OUT_DATED))
1624                 ns.pdsk = D_OUTDATED;
1625
1626         rcu_read_lock();
1627         if (ns.disk == D_CONSISTENT &&
1628             (ns.pdsk == D_OUTDATED || rcu_dereference(mdev->ldev->disk_conf)->fencing == FP_DONT_CARE))
1629                 ns.disk = D_UP_TO_DATE;
1630
1631         /* All tests on MDF_PRIMARY_IND, MDF_CONNECTED_IND,
1632            MDF_CONSISTENT and MDF_WAS_UP_TO_DATE must happen before
1633            this point, because drbd_request_state() modifies these
1634            flags. */
1635
1636         if (rcu_dereference(mdev->ldev->disk_conf)->al_updates)
1637                 mdev->ldev->md.flags &= ~MDF_AL_DISABLED;
1638         else
1639                 mdev->ldev->md.flags |= MDF_AL_DISABLED;
1640
1641         rcu_read_unlock();
1642
1643         /* In case we are C_CONNECTED postpone any decision on the new disk
1644            state after the negotiation phase. */
1645         if (mdev->state.conn == C_CONNECTED) {
1646                 mdev->new_state_tmp.i = ns.i;
1647                 ns.i = os.i;
1648                 ns.disk = D_NEGOTIATING;
1649
1650                 /* We expect to receive up-to-date UUIDs soon.
1651                    To avoid a race in receive_state, free p_uuid while
1652                    holding req_lock. I.e. atomic with the state change */
1653                 kfree(mdev->p_uuid);
1654                 mdev->p_uuid = NULL;
1655         }
1656
1657         rv = _drbd_set_state(mdev, ns, CS_VERBOSE, NULL);
1658         spin_unlock_irq(&mdev->tconn->req_lock);
1659
1660         if (rv < SS_SUCCESS)
1661                 goto force_diskless_dec;
1662
1663         mod_timer(&mdev->request_timer, jiffies + HZ);
1664
1665         if (mdev->state.role == R_PRIMARY)
1666                 mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
1667         else
1668                 mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
1669
1670         drbd_md_mark_dirty(mdev);
1671         drbd_md_sync(mdev);
1672
1673         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
1674         put_ldev(mdev);
1675         conn_reconfig_done(mdev->tconn);
1676         drbd_adm_finish(info, retcode);
1677         return 0;
1678
1679  force_diskless_dec:
1680         put_ldev(mdev);
1681  force_diskless:
1682         drbd_force_state(mdev, NS(disk, D_DISKLESS));
1683         drbd_md_sync(mdev);
1684  fail:
1685         conn_reconfig_done(mdev->tconn);
1686         if (nbc) {
1687                 if (nbc->backing_bdev)
1688                         blkdev_put(nbc->backing_bdev,
1689                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1690                 if (nbc->md_bdev)
1691                         blkdev_put(nbc->md_bdev,
1692                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1693                 kfree(nbc);
1694         }
1695         kfree(new_disk_conf);
1696         lc_destroy(resync_lru);
1697         kfree(new_plan);
1698
1699  finish:
1700         drbd_adm_finish(info, retcode);
1701         return 0;
1702 }
1703
1704 static int adm_detach(struct drbd_conf *mdev, int force)
1705 {
1706         enum drbd_state_rv retcode;
1707         int ret;
1708
1709         if (force) {
1710                 set_bit(FORCE_DETACH, &mdev->flags);
1711                 drbd_force_state(mdev, NS(disk, D_FAILED));
1712                 retcode = SS_SUCCESS;
1713                 goto out;
1714         }
1715
1716         drbd_suspend_io(mdev); /* so no-one is stuck in drbd_al_begin_io */
1717         drbd_md_get_buffer(mdev); /* make sure there is no in-flight meta-data IO */
1718         retcode = drbd_request_state(mdev, NS(disk, D_FAILED));
1719         drbd_md_put_buffer(mdev);
1720         /* D_FAILED will transition to DISKLESS. */
1721         ret = wait_event_interruptible(mdev->misc_wait,
1722                         mdev->state.disk != D_FAILED);
1723         drbd_resume_io(mdev);
1724         if ((int)retcode == (int)SS_IS_DISKLESS)
1725                 retcode = SS_NOTHING_TO_DO;
1726         if (ret)
1727                 retcode = ERR_INTR;
1728 out:
1729         return retcode;
1730 }
1731
1732 /* Detaching the disk is a process in multiple stages.  First we need to lock
1733  * out application IO, in-flight IO, IO stuck in drbd_al_begin_io.
1734  * Then we transition to D_DISKLESS, and wait for put_ldev() to return all
1735  * internal references as well.
1736  * Only then we have finally detached. */
1737 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info)
1738 {
1739         enum drbd_ret_code retcode;
1740         struct detach_parms parms = { };
1741         int err;
1742
1743         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1744         if (!adm_ctx.reply_skb)
1745                 return retcode;
1746         if (retcode != NO_ERROR)
1747                 goto out;
1748
1749         if (info->attrs[DRBD_NLA_DETACH_PARMS]) {
1750                 err = detach_parms_from_attrs(&parms, info);
1751                 if (err) {
1752                         retcode = ERR_MANDATORY_TAG;
1753                         drbd_msg_put_info(from_attrs_err_to_txt(err));
1754                         goto out;
1755                 }
1756         }
1757
1758         retcode = adm_detach(adm_ctx.mdev, parms.force_detach);
1759 out:
1760         drbd_adm_finish(info, retcode);
1761         return 0;
1762 }
1763
1764 static bool conn_resync_running(struct drbd_tconn *tconn)
1765 {
1766         struct drbd_conf *mdev;
1767         bool rv = false;
1768         int vnr;
1769
1770         rcu_read_lock();
1771         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1772                 if (mdev->state.conn == C_SYNC_SOURCE ||
1773                     mdev->state.conn == C_SYNC_TARGET ||
1774                     mdev->state.conn == C_PAUSED_SYNC_S ||
1775                     mdev->state.conn == C_PAUSED_SYNC_T) {
1776                         rv = true;
1777                         break;
1778                 }
1779         }
1780         rcu_read_unlock();
1781
1782         return rv;
1783 }
1784
1785 static bool conn_ov_running(struct drbd_tconn *tconn)
1786 {
1787         struct drbd_conf *mdev;
1788         bool rv = false;
1789         int vnr;
1790
1791         rcu_read_lock();
1792         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1793                 if (mdev->state.conn == C_VERIFY_S ||
1794                     mdev->state.conn == C_VERIFY_T) {
1795                         rv = true;
1796                         break;
1797                 }
1798         }
1799         rcu_read_unlock();
1800
1801         return rv;
1802 }
1803
1804 static enum drbd_ret_code
1805 _check_net_options(struct drbd_tconn *tconn, struct net_conf *old_conf, struct net_conf *new_conf)
1806 {
1807         struct drbd_conf *mdev;
1808         int i;
1809
1810         if (old_conf && tconn->cstate == C_WF_REPORT_PARAMS && tconn->agreed_pro_version < 100) {
1811                 if (new_conf->wire_protocol != old_conf->wire_protocol)
1812                         return ERR_NEED_APV_100;
1813
1814                 if (new_conf->two_primaries != old_conf->two_primaries)
1815                         return ERR_NEED_APV_100;
1816
1817                 if (strcmp(new_conf->integrity_alg, old_conf->integrity_alg))
1818                         return ERR_NEED_APV_100;
1819         }
1820
1821         if (!new_conf->two_primaries &&
1822             conn_highest_role(tconn) == R_PRIMARY &&
1823             conn_highest_peer(tconn) == R_PRIMARY)
1824                 return ERR_NEED_ALLOW_TWO_PRI;
1825
1826         if (new_conf->two_primaries &&
1827             (new_conf->wire_protocol != DRBD_PROT_C))
1828                 return ERR_NOT_PROTO_C;
1829
1830         idr_for_each_entry(&tconn->volumes, mdev, i) {
1831                 if (get_ldev(mdev)) {
1832                         enum drbd_fencing_p fp = rcu_dereference(mdev->ldev->disk_conf)->fencing;
1833                         put_ldev(mdev);
1834                         if (new_conf->wire_protocol == DRBD_PROT_A && fp == FP_STONITH)
1835                                 return ERR_STONITH_AND_PROT_A;
1836                 }
1837                 if (mdev->state.role == R_PRIMARY && new_conf->discard_my_data)
1838                         return ERR_DISCARD_IMPOSSIBLE;
1839         }
1840
1841         if (new_conf->on_congestion != OC_BLOCK && new_conf->wire_protocol != DRBD_PROT_A)
1842                 return ERR_CONG_NOT_PROTO_A;
1843
1844         return NO_ERROR;
1845 }
1846
1847 static enum drbd_ret_code
1848 check_net_options(struct drbd_tconn *tconn, struct net_conf *new_conf)
1849 {
1850         static enum drbd_ret_code rv;
1851         struct drbd_conf *mdev;
1852         int i;
1853
1854         rcu_read_lock();
1855         rv = _check_net_options(tconn, rcu_dereference(tconn->net_conf), new_conf);
1856         rcu_read_unlock();
1857
1858         /* tconn->volumes protected by genl_lock() here */
1859         idr_for_each_entry(&tconn->volumes, mdev, i) {
1860                 if (!mdev->bitmap) {
1861                         if(drbd_bm_init(mdev))
1862                                 return ERR_NOMEM;
1863                 }
1864         }
1865
1866         return rv;
1867 }
1868
1869 struct crypto {
1870         struct crypto_hash *verify_tfm;
1871         struct crypto_hash *csums_tfm;
1872         struct crypto_hash *cram_hmac_tfm;
1873         struct crypto_hash *integrity_tfm;
1874 };
1875
1876 static int
1877 alloc_hash(struct crypto_hash **tfm, char *tfm_name, int err_alg)
1878 {
1879         if (!tfm_name[0])
1880                 return NO_ERROR;
1881
1882         *tfm = crypto_alloc_hash(tfm_name, 0, CRYPTO_ALG_ASYNC);
1883         if (IS_ERR(*tfm)) {
1884                 *tfm = NULL;
1885                 return err_alg;
1886         }
1887
1888         return NO_ERROR;
1889 }
1890
1891 static enum drbd_ret_code
1892 alloc_crypto(struct crypto *crypto, struct net_conf *new_conf)
1893 {
1894         char hmac_name[CRYPTO_MAX_ALG_NAME];
1895         enum drbd_ret_code rv;
1896
1897         rv = alloc_hash(&crypto->csums_tfm, new_conf->csums_alg,
1898                        ERR_CSUMS_ALG);
1899         if (rv != NO_ERROR)
1900                 return rv;
1901         rv = alloc_hash(&crypto->verify_tfm, new_conf->verify_alg,
1902                        ERR_VERIFY_ALG);
1903         if (rv != NO_ERROR)
1904                 return rv;
1905         rv = alloc_hash(&crypto->integrity_tfm, new_conf->integrity_alg,
1906                        ERR_INTEGRITY_ALG);
1907         if (rv != NO_ERROR)
1908                 return rv;
1909         if (new_conf->cram_hmac_alg[0] != 0) {
1910                 snprintf(hmac_name, CRYPTO_MAX_ALG_NAME, "hmac(%s)",
1911                          new_conf->cram_hmac_alg);
1912
1913                 rv = alloc_hash(&crypto->cram_hmac_tfm, hmac_name,
1914                                ERR_AUTH_ALG);
1915         }
1916
1917         return rv;
1918 }
1919
1920 static void free_crypto(struct crypto *crypto)
1921 {
1922         crypto_free_hash(crypto->cram_hmac_tfm);
1923         crypto_free_hash(crypto->integrity_tfm);
1924         crypto_free_hash(crypto->csums_tfm);
1925         crypto_free_hash(crypto->verify_tfm);
1926 }
1927
1928 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info)
1929 {
1930         enum drbd_ret_code retcode;
1931         struct drbd_tconn *tconn;
1932         struct net_conf *old_conf, *new_conf = NULL;
1933         int err;
1934         int ovr; /* online verify running */
1935         int rsr; /* re-sync running */
1936         struct crypto crypto = { };
1937
1938         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONNECTION);
1939         if (!adm_ctx.reply_skb)
1940                 return retcode;
1941         if (retcode != NO_ERROR)
1942                 goto out;
1943
1944         tconn = adm_ctx.tconn;
1945
1946         new_conf = kzalloc(sizeof(struct net_conf), GFP_KERNEL);
1947         if (!new_conf) {
1948                 retcode = ERR_NOMEM;
1949                 goto out;
1950         }
1951
1952         conn_reconfig_start(tconn);
1953
1954         mutex_lock(&tconn->data.mutex);
1955         mutex_lock(&tconn->conf_update);
1956         old_conf = tconn->net_conf;
1957
1958         if (!old_conf) {
1959                 drbd_msg_put_info("net conf missing, try connect");
1960                 retcode = ERR_INVALID_REQUEST;
1961                 goto fail;
1962         }
1963
1964         *new_conf = *old_conf;
1965         if (should_set_defaults(info))
1966                 set_net_conf_defaults(new_conf);
1967
1968         err = net_conf_from_attrs_for_change(new_conf, info);
1969         if (err && err != -ENOMSG) {
1970                 retcode = ERR_MANDATORY_TAG;
1971                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1972                 goto fail;
1973         }
1974
1975         retcode = check_net_options(tconn, new_conf);
1976         if (retcode != NO_ERROR)
1977                 goto fail;
1978
1979         /* re-sync running */
1980         rsr = conn_resync_running(tconn);
1981         if (rsr && strcmp(new_conf->csums_alg, old_conf->csums_alg)) {
1982                 retcode = ERR_CSUMS_RESYNC_RUNNING;
1983                 goto fail;
1984         }
1985
1986         /* online verify running */
1987         ovr = conn_ov_running(tconn);
1988         if (ovr && strcmp(new_conf->verify_alg, old_conf->verify_alg)) {
1989                 retcode = ERR_VERIFY_RUNNING;
1990                 goto fail;
1991         }
1992
1993         retcode = alloc_crypto(&crypto, new_conf);
1994         if (retcode != NO_ERROR)
1995                 goto fail;
1996
1997         rcu_assign_pointer(tconn->net_conf, new_conf);
1998
1999         if (!rsr) {
2000                 crypto_free_hash(tconn->csums_tfm);
2001                 tconn->csums_tfm = crypto.csums_tfm;
2002                 crypto.csums_tfm = NULL;
2003         }
2004         if (!ovr) {
2005                 crypto_free_hash(tconn->verify_tfm);
2006                 tconn->verify_tfm = crypto.verify_tfm;
2007                 crypto.verify_tfm = NULL;
2008         }
2009
2010         crypto_free_hash(tconn->integrity_tfm);
2011         tconn->integrity_tfm = crypto.integrity_tfm;
2012         if (tconn->cstate >= C_WF_REPORT_PARAMS && tconn->agreed_pro_version >= 100)
2013                 /* Do this without trying to take tconn->data.mutex again.  */
2014                 __drbd_send_protocol(tconn, P_PROTOCOL_UPDATE);
2015
2016         crypto_free_hash(tconn->cram_hmac_tfm);
2017         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
2018
2019         mutex_unlock(&tconn->conf_update);
2020         mutex_unlock(&tconn->data.mutex);
2021         synchronize_rcu();
2022         kfree(old_conf);
2023
2024         if (tconn->cstate >= C_WF_REPORT_PARAMS)
2025                 drbd_send_sync_param(minor_to_mdev(conn_lowest_minor(tconn)));
2026
2027         goto done;
2028
2029  fail:
2030         mutex_unlock(&tconn->conf_update);
2031         mutex_unlock(&tconn->data.mutex);
2032         free_crypto(&crypto);
2033         kfree(new_conf);
2034  done:
2035         conn_reconfig_done(tconn);
2036  out:
2037         drbd_adm_finish(info, retcode);
2038         return 0;
2039 }
2040
2041 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info)
2042 {
2043         struct drbd_conf *mdev;
2044         struct net_conf *old_conf, *new_conf = NULL;
2045         struct crypto crypto = { };
2046         struct drbd_tconn *tconn;
2047         enum drbd_ret_code retcode;
2048         int i;
2049         int err;
2050
2051         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
2052
2053         if (!adm_ctx.reply_skb)
2054                 return retcode;
2055         if (retcode != NO_ERROR)
2056                 goto out;
2057         if (!(adm_ctx.my_addr && adm_ctx.peer_addr)) {
2058                 drbd_msg_put_info("connection endpoint(s) missing");
2059                 retcode = ERR_INVALID_REQUEST;
2060                 goto out;
2061         }
2062
2063         /* No need for _rcu here. All reconfiguration is
2064          * strictly serialized on genl_lock(). We are protected against
2065          * concurrent reconfiguration/addition/deletion */
2066         list_for_each_entry(tconn, &drbd_tconns, all_tconn) {
2067                 if (nla_len(adm_ctx.my_addr) == tconn->my_addr_len &&
2068                     !memcmp(nla_data(adm_ctx.my_addr), &tconn->my_addr, tconn->my_addr_len)) {
2069                         retcode = ERR_LOCAL_ADDR;
2070                         goto out;
2071                 }
2072
2073                 if (nla_len(adm_ctx.peer_addr) == tconn->peer_addr_len &&
2074                     !memcmp(nla_data(adm_ctx.peer_addr), &tconn->peer_addr, tconn->peer_addr_len)) {
2075                         retcode = ERR_PEER_ADDR;
2076                         goto out;
2077                 }
2078         }
2079
2080         tconn = adm_ctx.tconn;
2081         conn_reconfig_start(tconn);
2082
2083         if (tconn->cstate > C_STANDALONE) {
2084                 retcode = ERR_NET_CONFIGURED;
2085                 goto fail;
2086         }
2087
2088         /* allocation not in the IO path, drbdsetup / netlink process context */
2089         new_conf = kzalloc(sizeof(*new_conf), GFP_KERNEL);
2090         if (!new_conf) {
2091                 retcode = ERR_NOMEM;
2092                 goto fail;
2093         }
2094
2095         set_net_conf_defaults(new_conf);
2096
2097         err = net_conf_from_attrs(new_conf, info);
2098         if (err && err != -ENOMSG) {
2099                 retcode = ERR_MANDATORY_TAG;
2100                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2101                 goto fail;
2102         }
2103
2104         retcode = check_net_options(tconn, new_conf);
2105         if (retcode != NO_ERROR)
2106                 goto fail;
2107
2108         retcode = alloc_crypto(&crypto, new_conf);
2109         if (retcode != NO_ERROR)
2110                 goto fail;
2111
2112         ((char *)new_conf->shared_secret)[SHARED_SECRET_MAX-1] = 0;
2113
2114         conn_flush_workqueue(tconn);
2115
2116         mutex_lock(&tconn->conf_update);
2117         old_conf = tconn->net_conf;
2118         if (old_conf) {
2119                 retcode = ERR_NET_CONFIGURED;
2120                 mutex_unlock(&tconn->conf_update);
2121                 goto fail;
2122         }
2123         rcu_assign_pointer(tconn->net_conf, new_conf);
2124
2125         conn_free_crypto(tconn);
2126         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
2127         tconn->integrity_tfm = crypto.integrity_tfm;
2128         tconn->csums_tfm = crypto.csums_tfm;
2129         tconn->verify_tfm = crypto.verify_tfm;
2130
2131         tconn->my_addr_len = nla_len(adm_ctx.my_addr);
2132         memcpy(&tconn->my_addr, nla_data(adm_ctx.my_addr), tconn->my_addr_len);
2133         tconn->peer_addr_len = nla_len(adm_ctx.peer_addr);
2134         memcpy(&tconn->peer_addr, nla_data(adm_ctx.peer_addr), tconn->peer_addr_len);
2135
2136         mutex_unlock(&tconn->conf_update);
2137
2138         rcu_read_lock();
2139         idr_for_each_entry(&tconn->volumes, mdev, i) {
2140                 mdev->send_cnt = 0;
2141                 mdev->recv_cnt = 0;
2142         }
2143         rcu_read_unlock();
2144
2145         retcode = conn_request_state(tconn, NS(conn, C_UNCONNECTED), CS_VERBOSE);
2146
2147         conn_reconfig_done(tconn);
2148         drbd_adm_finish(info, retcode);
2149         return 0;
2150
2151 fail:
2152         free_crypto(&crypto);
2153         kfree(new_conf);
2154
2155         conn_reconfig_done(tconn);
2156 out:
2157         drbd_adm_finish(info, retcode);
2158         return 0;
2159 }
2160
2161 static enum drbd_state_rv conn_try_disconnect(struct drbd_tconn *tconn, bool force)
2162 {
2163         enum drbd_state_rv rv;
2164
2165         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2166                         force ? CS_HARD : 0);
2167
2168         switch (rv) {
2169         case SS_NOTHING_TO_DO:
2170                 break;
2171         case SS_ALREADY_STANDALONE:
2172                 return SS_SUCCESS;
2173         case SS_PRIMARY_NOP:
2174                 /* Our state checking code wants to see the peer outdated. */
2175                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2176                                                 pdsk, D_OUTDATED), CS_VERBOSE);
2177                 break;
2178         case SS_CW_FAILED_BY_PEER:
2179                 /* The peer probably wants to see us outdated. */
2180                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2181                                                         disk, D_OUTDATED), 0);
2182                 if (rv == SS_IS_DISKLESS || rv == SS_LOWER_THAN_OUTDATED) {
2183                         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2184                                         CS_HARD);
2185                 }
2186                 break;
2187         default:;
2188                 /* no special handling necessary */
2189         }
2190
2191         if (rv >= SS_SUCCESS) {
2192                 enum drbd_state_rv rv2;
2193                 /* No one else can reconfigure the network while I am here.
2194                  * The state handling only uses drbd_thread_stop_nowait(),
2195                  * we want to really wait here until the receiver is no more.
2196                  */
2197                 drbd_thread_stop(&adm_ctx.tconn->receiver);
2198
2199                 /* Race breaker.  This additional state change request may be
2200                  * necessary, if this was a forced disconnect during a receiver
2201                  * restart.  We may have "killed" the receiver thread just
2202                  * after drbdd_init() returned.  Typically, we should be
2203                  * C_STANDALONE already, now, and this becomes a no-op.
2204                  */
2205                 rv2 = conn_request_state(tconn, NS(conn, C_STANDALONE),
2206                                 CS_VERBOSE | CS_HARD);
2207                 if (rv2 < SS_SUCCESS)
2208                         conn_err(tconn,
2209                                 "unexpected rv2=%d in conn_try_disconnect()\n",
2210                                 rv2);
2211         }
2212         return rv;
2213 }
2214
2215 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info)
2216 {
2217         struct disconnect_parms parms;
2218         struct drbd_tconn *tconn;
2219         enum drbd_state_rv rv;
2220         enum drbd_ret_code retcode;
2221         int err;
2222
2223         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONNECTION);
2224         if (!adm_ctx.reply_skb)
2225                 return retcode;
2226         if (retcode != NO_ERROR)
2227                 goto fail;
2228
2229         tconn = adm_ctx.tconn;
2230         memset(&parms, 0, sizeof(parms));
2231         if (info->attrs[DRBD_NLA_DISCONNECT_PARMS]) {
2232                 err = disconnect_parms_from_attrs(&parms, info);
2233                 if (err) {
2234                         retcode = ERR_MANDATORY_TAG;
2235                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2236                         goto fail;
2237                 }
2238         }
2239
2240         rv = conn_try_disconnect(tconn, parms.force_disconnect);
2241         if (rv < SS_SUCCESS)
2242                 retcode = rv;  /* FIXME: Type mismatch. */
2243         else
2244                 retcode = NO_ERROR;
2245  fail:
2246         drbd_adm_finish(info, retcode);
2247         return 0;
2248 }
2249
2250 void resync_after_online_grow(struct drbd_conf *mdev)
2251 {
2252         int iass; /* I am sync source */
2253
2254         dev_info(DEV, "Resync of new storage after online grow\n");
2255         if (mdev->state.role != mdev->state.peer)
2256                 iass = (mdev->state.role == R_PRIMARY);
2257         else
2258                 iass = test_bit(RESOLVE_CONFLICTS, &mdev->tconn->flags);
2259
2260         if (iass)
2261                 drbd_start_resync(mdev, C_SYNC_SOURCE);
2262         else
2263                 _drbd_request_state(mdev, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE + CS_SERIALIZE);
2264 }
2265
2266 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info)
2267 {
2268         struct disk_conf *old_disk_conf, *new_disk_conf = NULL;
2269         struct resize_parms rs;
2270         struct drbd_conf *mdev;
2271         enum drbd_ret_code retcode;
2272         enum determine_dev_size dd;
2273         enum dds_flags ddsf;
2274         sector_t u_size;
2275         int err;
2276
2277         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2278         if (!adm_ctx.reply_skb)
2279                 return retcode;
2280         if (retcode != NO_ERROR)
2281                 goto fail;
2282
2283         memset(&rs, 0, sizeof(struct resize_parms));
2284         if (info->attrs[DRBD_NLA_RESIZE_PARMS]) {
2285                 err = resize_parms_from_attrs(&rs, info);
2286                 if (err) {
2287                         retcode = ERR_MANDATORY_TAG;
2288                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2289                         goto fail;
2290                 }
2291         }
2292
2293         mdev = adm_ctx.mdev;
2294         if (mdev->state.conn > C_CONNECTED) {
2295                 retcode = ERR_RESIZE_RESYNC;
2296                 goto fail;
2297         }
2298
2299         if (mdev->state.role == R_SECONDARY &&
2300             mdev->state.peer == R_SECONDARY) {
2301                 retcode = ERR_NO_PRIMARY;
2302                 goto fail;
2303         }
2304
2305         if (!get_ldev(mdev)) {
2306                 retcode = ERR_NO_DISK;
2307                 goto fail;
2308         }
2309
2310         if (rs.no_resync && mdev->tconn->agreed_pro_version < 93) {
2311                 retcode = ERR_NEED_APV_93;
2312                 goto fail_ldev;
2313         }
2314
2315         rcu_read_lock();
2316         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
2317         rcu_read_unlock();
2318         if (u_size != (sector_t)rs.resize_size) {
2319                 new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
2320                 if (!new_disk_conf) {
2321                         retcode = ERR_NOMEM;
2322                         goto fail_ldev;
2323                 }
2324         }
2325
2326         if (mdev->ldev->known_size != drbd_get_capacity(mdev->ldev->backing_bdev))
2327                 mdev->ldev->known_size = drbd_get_capacity(mdev->ldev->backing_bdev);
2328
2329         if (new_disk_conf) {
2330                 mutex_lock(&mdev->tconn->conf_update);
2331                 old_disk_conf = mdev->ldev->disk_conf;
2332                 *new_disk_conf = *old_disk_conf;
2333                 new_disk_conf->disk_size = (sector_t)rs.resize_size;
2334                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
2335                 mutex_unlock(&mdev->tconn->conf_update);
2336                 synchronize_rcu();
2337                 kfree(old_disk_conf);
2338         }
2339
2340         ddsf = (rs.resize_force ? DDSF_FORCED : 0) | (rs.no_resync ? DDSF_NO_RESYNC : 0);
2341         dd = drbd_determine_dev_size(mdev, ddsf);
2342         drbd_md_sync(mdev);
2343         put_ldev(mdev);
2344         if (dd == dev_size_error) {
2345                 retcode = ERR_NOMEM_BITMAP;
2346                 goto fail;
2347         }
2348
2349         if (mdev->state.conn == C_CONNECTED) {
2350                 if (dd == grew)
2351                         set_bit(RESIZE_PENDING, &mdev->flags);
2352
2353                 drbd_send_uuids(mdev);
2354                 drbd_send_sizes(mdev, 1, ddsf);
2355         }
2356
2357  fail:
2358         drbd_adm_finish(info, retcode);
2359         return 0;
2360
2361  fail_ldev:
2362         put_ldev(mdev);
2363         goto fail;
2364 }
2365
2366 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info)
2367 {
2368         enum drbd_ret_code retcode;
2369         struct drbd_tconn *tconn;
2370         struct res_opts res_opts;
2371         int err;
2372
2373         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
2374         if (!adm_ctx.reply_skb)
2375                 return retcode;
2376         if (retcode != NO_ERROR)
2377                 goto fail;
2378         tconn = adm_ctx.tconn;
2379
2380         res_opts = tconn->res_opts;
2381         if (should_set_defaults(info))
2382                 set_res_opts_defaults(&res_opts);
2383
2384         err = res_opts_from_attrs(&res_opts, info);
2385         if (err && err != -ENOMSG) {
2386                 retcode = ERR_MANDATORY_TAG;
2387                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2388                 goto fail;
2389         }
2390
2391         err = set_resource_options(tconn, &res_opts);
2392         if (err) {
2393                 retcode = ERR_INVALID_REQUEST;
2394                 if (err == -ENOMEM)
2395                         retcode = ERR_NOMEM;
2396         }
2397
2398 fail:
2399         drbd_adm_finish(info, retcode);
2400         return 0;
2401 }
2402
2403 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info)
2404 {
2405         struct drbd_conf *mdev;
2406         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2407
2408         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2409         if (!adm_ctx.reply_skb)
2410                 return retcode;
2411         if (retcode != NO_ERROR)
2412                 goto out;
2413
2414         mdev = adm_ctx.mdev;
2415
2416         /* If there is still bitmap IO pending, probably because of a previous
2417          * resync just being finished, wait for it before requesting a new resync.
2418          * Also wait for it's after_state_ch(). */
2419         drbd_suspend_io(mdev);
2420         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2421         drbd_flush_workqueue(mdev);
2422
2423         retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T), CS_ORDERED);
2424
2425         if (retcode < SS_SUCCESS && retcode != SS_NEED_CONNECTION)
2426                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2427
2428         while (retcode == SS_NEED_CONNECTION) {
2429                 spin_lock_irq(&mdev->tconn->req_lock);
2430                 if (mdev->state.conn < C_CONNECTED)
2431                         retcode = _drbd_set_state(_NS(mdev, disk, D_INCONSISTENT), CS_VERBOSE, NULL);
2432                 spin_unlock_irq(&mdev->tconn->req_lock);
2433
2434                 if (retcode != SS_NEED_CONNECTION)
2435                         break;
2436
2437                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2438         }
2439         drbd_resume_io(mdev);
2440
2441 out:
2442         drbd_adm_finish(info, retcode);
2443         return 0;
2444 }
2445
2446 static int drbd_adm_simple_request_state(struct sk_buff *skb, struct genl_info *info,
2447                 union drbd_state mask, union drbd_state val)
2448 {
2449         enum drbd_ret_code retcode;
2450
2451         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2452         if (!adm_ctx.reply_skb)
2453                 return retcode;
2454         if (retcode != NO_ERROR)
2455                 goto out;
2456
2457         retcode = drbd_request_state(adm_ctx.mdev, mask, val);
2458 out:
2459         drbd_adm_finish(info, retcode);
2460         return 0;
2461 }
2462
2463 static int drbd_bmio_set_susp_al(struct drbd_conf *mdev)
2464 {
2465         int rv;
2466
2467         rv = drbd_bmio_set_n_write(mdev);
2468         drbd_suspend_al(mdev);
2469         return rv;
2470 }
2471
2472 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info)
2473 {
2474         int retcode; /* drbd_ret_code, drbd_state_rv */
2475         struct drbd_conf *mdev;
2476
2477         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2478         if (!adm_ctx.reply_skb)
2479                 return retcode;
2480         if (retcode != NO_ERROR)
2481                 goto out;
2482
2483         mdev = adm_ctx.mdev;
2484
2485         /* If there is still bitmap IO pending, probably because of a previous
2486          * resync just being finished, wait for it before requesting a new resync.
2487          * Also wait for it's after_state_ch(). */
2488         drbd_suspend_io(mdev);
2489         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2490         drbd_flush_workqueue(mdev);
2491
2492         retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_S), CS_ORDERED);
2493         if (retcode < SS_SUCCESS) {
2494                 if (retcode == SS_NEED_CONNECTION && mdev->state.role == R_PRIMARY) {
2495                         /* The peer will get a resync upon connect anyways.
2496                          * Just make that into a full resync. */
2497                         retcode = drbd_request_state(mdev, NS(pdsk, D_INCONSISTENT));
2498                         if (retcode >= SS_SUCCESS) {
2499                                 if (drbd_bitmap_io(mdev, &drbd_bmio_set_susp_al,
2500                                                    "set_n_write from invalidate_peer",
2501                                                    BM_LOCKED_SET_ALLOWED))
2502                                         retcode = ERR_IO_MD_DISK;
2503                         }
2504                 } else
2505                         retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_S));
2506         }
2507         drbd_resume_io(mdev);
2508
2509 out:
2510         drbd_adm_finish(info, retcode);
2511         return 0;
2512 }
2513
2514 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info)
2515 {
2516         enum drbd_ret_code retcode;
2517
2518         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2519         if (!adm_ctx.reply_skb)
2520                 return retcode;
2521         if (retcode != NO_ERROR)
2522                 goto out;
2523
2524         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 1)) == SS_NOTHING_TO_DO)
2525                 retcode = ERR_PAUSE_IS_SET;
2526 out:
2527         drbd_adm_finish(info, retcode);
2528         return 0;
2529 }
2530
2531 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info)
2532 {
2533         union drbd_dev_state s;
2534         enum drbd_ret_code retcode;
2535
2536         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2537         if (!adm_ctx.reply_skb)
2538                 return retcode;
2539         if (retcode != NO_ERROR)
2540                 goto out;
2541
2542         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 0)) == SS_NOTHING_TO_DO) {
2543                 s = adm_ctx.mdev->state;
2544                 if (s.conn == C_PAUSED_SYNC_S || s.conn == C_PAUSED_SYNC_T) {
2545                         retcode = s.aftr_isp ? ERR_PIC_AFTER_DEP :
2546                                   s.peer_isp ? ERR_PIC_PEER_DEP : ERR_PAUSE_IS_CLEAR;
2547                 } else {
2548                         retcode = ERR_PAUSE_IS_CLEAR;
2549                 }
2550         }
2551
2552 out:
2553         drbd_adm_finish(info, retcode);
2554         return 0;
2555 }
2556
2557 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info)
2558 {
2559         return drbd_adm_simple_request_state(skb, info, NS(susp, 1));
2560 }
2561
2562 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info)
2563 {
2564         struct drbd_conf *mdev;
2565         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2566
2567         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2568         if (!adm_ctx.reply_skb)
2569                 return retcode;
2570         if (retcode != NO_ERROR)
2571                 goto out;
2572
2573         mdev = adm_ctx.mdev;
2574         if (test_bit(NEW_CUR_UUID, &mdev->flags)) {
2575                 drbd_uuid_new_current(mdev);
2576                 clear_bit(NEW_CUR_UUID, &mdev->flags);
2577         }
2578         drbd_suspend_io(mdev);
2579         retcode = drbd_request_state(mdev, NS3(susp, 0, susp_nod, 0, susp_fen, 0));
2580         if (retcode == SS_SUCCESS) {
2581                 if (mdev->state.conn < C_CONNECTED)
2582                         tl_clear(mdev->tconn);
2583                 if (mdev->state.disk == D_DISKLESS || mdev->state.disk == D_FAILED)
2584                         tl_restart(mdev->tconn, FAIL_FROZEN_DISK_IO);
2585         }
2586         drbd_resume_io(mdev);
2587
2588 out:
2589         drbd_adm_finish(info, retcode);
2590         return 0;
2591 }
2592
2593 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info)
2594 {
2595         return drbd_adm_simple_request_state(skb, info, NS(disk, D_OUTDATED));
2596 }
2597
2598 int nla_put_drbd_cfg_context(struct sk_buff *skb, struct drbd_tconn *tconn, unsigned vnr)
2599 {
2600         struct nlattr *nla;
2601         nla = nla_nest_start(skb, DRBD_NLA_CFG_CONTEXT);
2602         if (!nla)
2603                 goto nla_put_failure;
2604         if (vnr != VOLUME_UNSPECIFIED &&
2605             nla_put_u32(skb, T_ctx_volume, vnr))
2606                 goto nla_put_failure;
2607         if (nla_put_string(skb, T_ctx_resource_name, tconn->name))
2608                 goto nla_put_failure;
2609         if (tconn->my_addr_len &&
2610             nla_put(skb, T_ctx_my_addr, tconn->my_addr_len, &tconn->my_addr))
2611                 goto nla_put_failure;
2612         if (tconn->peer_addr_len &&
2613             nla_put(skb, T_ctx_peer_addr, tconn->peer_addr_len, &tconn->peer_addr))
2614                 goto nla_put_failure;
2615         nla_nest_end(skb, nla);
2616         return 0;
2617
2618 nla_put_failure:
2619         if (nla)
2620                 nla_nest_cancel(skb, nla);
2621         return -EMSGSIZE;
2622 }
2623
2624 int nla_put_status_info(struct sk_buff *skb, struct drbd_conf *mdev,
2625                 const struct sib_info *sib)
2626 {
2627         struct state_info *si = NULL; /* for sizeof(si->member); */
2628         struct net_conf *nc;
2629         struct nlattr *nla;
2630         int got_ldev;
2631         int err = 0;
2632         int exclude_sensitive;
2633
2634         /* If sib != NULL, this is drbd_bcast_event, which anyone can listen
2635          * to.  So we better exclude_sensitive information.
2636          *
2637          * If sib == NULL, this is drbd_adm_get_status, executed synchronously
2638          * in the context of the requesting user process. Exclude sensitive
2639          * information, unless current has superuser.
2640          *
2641          * NOTE: for drbd_adm_get_status_all(), this is a netlink dump, and
2642          * relies on the current implementation of netlink_dump(), which
2643          * executes the dump callback successively from netlink_recvmsg(),
2644          * always in the context of the receiving process */
2645         exclude_sensitive = sib || !capable(CAP_SYS_ADMIN);
2646
2647         got_ldev = get_ldev(mdev);
2648
2649         /* We need to add connection name and volume number information still.
2650          * Minor number is in drbd_genlmsghdr. */
2651         if (nla_put_drbd_cfg_context(skb, mdev->tconn, mdev->vnr))
2652                 goto nla_put_failure;
2653
2654         if (res_opts_to_skb(skb, &mdev->tconn->res_opts, exclude_sensitive))
2655                 goto nla_put_failure;
2656
2657         rcu_read_lock();
2658         if (got_ldev)
2659                 if (disk_conf_to_skb(skb, rcu_dereference(mdev->ldev->disk_conf), exclude_sensitive))
2660                         goto nla_put_failure;
2661
2662         nc = rcu_dereference(mdev->tconn->net_conf);
2663         if (nc)
2664                 err = net_conf_to_skb(skb, nc, exclude_sensitive);
2665         rcu_read_unlock();
2666         if (err)
2667                 goto nla_put_failure;
2668
2669         nla = nla_nest_start(skb, DRBD_NLA_STATE_INFO);
2670         if (!nla)
2671                 goto nla_put_failure;
2672         if (nla_put_u32(skb, T_sib_reason, sib ? sib->sib_reason : SIB_GET_STATUS_REPLY) ||
2673             nla_put_u32(skb, T_current_state, mdev->state.i) ||
2674             nla_put_u64(skb, T_ed_uuid, mdev->ed_uuid) ||
2675             nla_put_u64(skb, T_capacity, drbd_get_capacity(mdev->this_bdev)) ||
2676             nla_put_u64(skb, T_send_cnt, mdev->send_cnt) ||
2677             nla_put_u64(skb, T_recv_cnt, mdev->recv_cnt) ||
2678             nla_put_u64(skb, T_read_cnt, mdev->read_cnt) ||
2679             nla_put_u64(skb, T_writ_cnt, mdev->writ_cnt) ||
2680             nla_put_u64(skb, T_al_writ_cnt, mdev->al_writ_cnt) ||
2681             nla_put_u64(skb, T_bm_writ_cnt, mdev->bm_writ_cnt) ||
2682             nla_put_u32(skb, T_ap_bio_cnt, atomic_read(&mdev->ap_bio_cnt)) ||
2683             nla_put_u32(skb, T_ap_pending_cnt, atomic_read(&mdev->ap_pending_cnt)) ||
2684             nla_put_u32(skb, T_rs_pending_cnt, atomic_read(&mdev->rs_pending_cnt)))
2685                 goto nla_put_failure;
2686
2687         if (got_ldev) {
2688                 int err;
2689
2690                 spin_lock_irq(&mdev->ldev->md.uuid_lock);
2691                 err = nla_put(skb, T_uuids, sizeof(si->uuids), mdev->ldev->md.uuid);
2692                 spin_unlock_irq(&mdev->ldev->md.uuid_lock);
2693
2694                 if (err)
2695                         goto nla_put_failure;
2696
2697                 if (nla_put_u32(skb, T_disk_flags, mdev->ldev->md.flags) ||
2698                     nla_put_u64(skb, T_bits_total, drbd_bm_bits(mdev)) ||
2699                     nla_put_u64(skb, T_bits_oos, drbd_bm_total_weight(mdev)))
2700                         goto nla_put_failure;
2701                 if (C_SYNC_SOURCE <= mdev->state.conn &&
2702                     C_PAUSED_SYNC_T >= mdev->state.conn) {
2703                         if (nla_put_u64(skb, T_bits_rs_total, mdev->rs_total) ||
2704                             nla_put_u64(skb, T_bits_rs_failed, mdev->rs_failed))
2705                                 goto nla_put_failure;
2706                 }
2707         }
2708
2709         if (sib) {
2710                 switch(sib->sib_reason) {
2711                 case SIB_SYNC_PROGRESS:
2712                 case SIB_GET_STATUS_REPLY:
2713                         break;
2714                 case SIB_STATE_CHANGE:
2715                         if (nla_put_u32(skb, T_prev_state, sib->os.i) ||
2716                             nla_put_u32(skb, T_new_state, sib->ns.i))
2717                                 goto nla_put_failure;
2718                         break;
2719                 case SIB_HELPER_POST:
2720                         if (nla_put_u32(skb, T_helper_exit_code,
2721                                         sib->helper_exit_code))
2722                                 goto nla_put_failure;
2723                         /* fall through */
2724                 case SIB_HELPER_PRE:
2725                         if (nla_put_string(skb, T_helper, sib->helper_name))
2726                                 goto nla_put_failure;
2727                         break;
2728                 }
2729         }
2730         nla_nest_end(skb, nla);
2731
2732         if (0)
2733 nla_put_failure:
2734                 err = -EMSGSIZE;
2735         if (got_ldev)
2736                 put_ldev(mdev);
2737         return err;
2738 }
2739
2740 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info)
2741 {
2742         enum drbd_ret_code retcode;
2743         int err;
2744
2745         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2746         if (!adm_ctx.reply_skb)
2747                 return retcode;
2748         if (retcode != NO_ERROR)
2749                 goto out;
2750
2751         err = nla_put_status_info(adm_ctx.reply_skb, adm_ctx.mdev, NULL);
2752         if (err) {
2753                 nlmsg_free(adm_ctx.reply_skb);
2754                 return err;
2755         }
2756 out:
2757         drbd_adm_finish(info, retcode);
2758         return 0;
2759 }
2760
2761 int get_one_status(struct sk_buff *skb, struct netlink_callback *cb)
2762 {
2763         struct drbd_conf *mdev;
2764         struct drbd_genlmsghdr *dh;
2765         struct drbd_tconn *pos = (struct drbd_tconn*)cb->args[0];
2766         struct drbd_tconn *tconn = NULL;
2767         struct drbd_tconn *tmp;
2768         unsigned volume = cb->args[1];
2769
2770         /* Open coded, deferred, iteration:
2771          * list_for_each_entry_safe(tconn, tmp, &drbd_tconns, all_tconn) {
2772          *      idr_for_each_entry(&tconn->volumes, mdev, i) {
2773          *        ...
2774          *      }
2775          * }
2776          * where tconn is cb->args[0];
2777          * and i is cb->args[1];
2778          *
2779          * cb->args[2] indicates if we shall loop over all resources,
2780          * or just dump all volumes of a single resource.
2781          *
2782          * This may miss entries inserted after this dump started,
2783          * or entries deleted before they are reached.
2784          *
2785          * We need to make sure the mdev won't disappear while
2786          * we are looking at it, and revalidate our iterators
2787          * on each iteration.
2788          */
2789
2790         /* synchronize with conn_create()/conn_destroy() */
2791         rcu_read_lock();
2792         /* revalidate iterator position */
2793         list_for_each_entry_rcu(tmp, &drbd_tconns, all_tconn) {
2794                 if (pos == NULL) {
2795                         /* first iteration */
2796                         pos = tmp;
2797                         tconn = pos;
2798                         break;
2799                 }
2800                 if (tmp == pos) {
2801                         tconn = pos;
2802                         break;
2803                 }
2804         }
2805         if (tconn) {
2806 next_tconn:
2807                 mdev = idr_get_next(&tconn->volumes, &volume);
2808                 if (!mdev) {
2809                         /* No more volumes to dump on this tconn.
2810                          * Advance tconn iterator. */
2811                         pos = list_entry_rcu(tconn->all_tconn.next,
2812                                              struct drbd_tconn, all_tconn);
2813                         /* Did we dump any volume on this tconn yet? */
2814                         if (volume != 0) {
2815                                 /* If we reached the end of the list,
2816                                  * or only a single resource dump was requested,
2817                                  * we are done. */
2818                                 if (&pos->all_tconn == &drbd_tconns || cb->args[2])
2819                                         goto out;
2820                                 volume = 0;
2821                                 tconn = pos;
2822                                 goto next_tconn;
2823                         }
2824                 }
2825
2826                 dh = genlmsg_put(skb, NETLINK_CB(cb->skb).portid,
2827                                 cb->nlh->nlmsg_seq, &drbd_genl_family,
2828                                 NLM_F_MULTI, DRBD_ADM_GET_STATUS);
2829                 if (!dh)
2830                         goto out;
2831
2832                 if (!mdev) {
2833                         /* This is a tconn without a single volume.
2834                          * Suprisingly enough, it may have a network
2835                          * configuration. */
2836                         struct net_conf *nc;
2837                         dh->minor = -1U;
2838                         dh->ret_code = NO_ERROR;
2839                         if (nla_put_drbd_cfg_context(skb, tconn, VOLUME_UNSPECIFIED))
2840                                 goto cancel;
2841                         nc = rcu_dereference(tconn->net_conf);
2842                         if (nc && net_conf_to_skb(skb, nc, 1) != 0)
2843                                 goto cancel;
2844                         goto done;
2845                 }
2846
2847                 D_ASSERT(mdev->vnr == volume);
2848                 D_ASSERT(mdev->tconn == tconn);
2849
2850                 dh->minor = mdev_to_minor(mdev);
2851                 dh->ret_code = NO_ERROR;
2852
2853                 if (nla_put_status_info(skb, mdev, NULL)) {
2854 cancel:
2855                         genlmsg_cancel(skb, dh);
2856                         goto out;
2857                 }
2858 done:
2859                 genlmsg_end(skb, dh);
2860         }
2861
2862 out:
2863         rcu_read_unlock();
2864         /* where to start the next iteration */
2865         cb->args[0] = (long)pos;
2866         cb->args[1] = (pos == tconn) ? volume + 1 : 0;
2867
2868         /* No more tconns/volumes/minors found results in an empty skb.
2869          * Which will terminate the dump. */
2870         return skb->len;
2871 }
2872
2873 /*
2874  * Request status of all resources, or of all volumes within a single resource.
2875  *
2876  * This is a dump, as the answer may not fit in a single reply skb otherwise.
2877  * Which means we cannot use the family->attrbuf or other such members, because
2878  * dump is NOT protected by the genl_lock().  During dump, we only have access
2879  * to the incoming skb, and need to opencode "parsing" of the nlattr payload.
2880  *
2881  * Once things are setup properly, we call into get_one_status().
2882  */
2883 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb)
2884 {
2885         const unsigned hdrlen = GENL_HDRLEN + GENL_MAGIC_FAMILY_HDRSZ;
2886         struct nlattr *nla;
2887         const char *resource_name;
2888         struct drbd_tconn *tconn;
2889         int maxtype;
2890
2891         /* Is this a followup call? */
2892         if (cb->args[0]) {
2893                 /* ... of a single resource dump,
2894                  * and the resource iterator has been advanced already? */
2895                 if (cb->args[2] && cb->args[2] != cb->args[0])
2896                         return 0; /* DONE. */
2897                 goto dump;
2898         }
2899
2900         /* First call (from netlink_dump_start).  We need to figure out
2901          * which resource(s) the user wants us to dump. */
2902         nla = nla_find(nlmsg_attrdata(cb->nlh, hdrlen),
2903                         nlmsg_attrlen(cb->nlh, hdrlen),
2904                         DRBD_NLA_CFG_CONTEXT);
2905
2906         /* No explicit context given.  Dump all. */
2907         if (!nla)
2908                 goto dump;
2909         maxtype = ARRAY_SIZE(drbd_cfg_context_nl_policy) - 1;
2910         nla = drbd_nla_find_nested(maxtype, nla, __nla_type(T_ctx_resource_name));
2911         if (IS_ERR(nla))
2912                 return PTR_ERR(nla);
2913         /* context given, but no name present? */
2914         if (!nla)
2915                 return -EINVAL;
2916         resource_name = nla_data(nla);
2917         tconn = conn_get_by_name(resource_name);
2918
2919         if (!tconn)
2920                 return -ENODEV;
2921
2922         kref_put(&tconn->kref, &conn_destroy); /* get_one_status() (re)validates tconn by itself */
2923
2924         /* prime iterators, and set "filter" mode mark:
2925          * only dump this tconn. */
2926         cb->args[0] = (long)tconn;
2927         /* cb->args[1] = 0; passed in this way. */
2928         cb->args[2] = (long)tconn;
2929
2930 dump:
2931         return get_one_status(skb, cb);
2932 }
2933
2934 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info)
2935 {
2936         enum drbd_ret_code retcode;
2937         struct timeout_parms tp;
2938         int err;
2939
2940         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2941         if (!adm_ctx.reply_skb)
2942                 return retcode;
2943         if (retcode != NO_ERROR)
2944                 goto out;
2945
2946         tp.timeout_type =
2947                 adm_ctx.mdev->state.pdsk == D_OUTDATED ? UT_PEER_OUTDATED :
2948                 test_bit(USE_DEGR_WFC_T, &adm_ctx.mdev->flags) ? UT_DEGRADED :
2949                 UT_DEFAULT;
2950
2951         err = timeout_parms_to_priv_skb(adm_ctx.reply_skb, &tp);
2952         if (err) {
2953                 nlmsg_free(adm_ctx.reply_skb);
2954                 return err;
2955         }
2956 out:
2957         drbd_adm_finish(info, retcode);
2958         return 0;
2959 }
2960
2961 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info)
2962 {
2963         struct drbd_conf *mdev;
2964         enum drbd_ret_code retcode;
2965         struct start_ov_parms parms;
2966
2967         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2968         if (!adm_ctx.reply_skb)
2969                 return retcode;
2970         if (retcode != NO_ERROR)
2971                 goto out;
2972
2973         mdev = adm_ctx.mdev;
2974
2975         /* resume from last known position, if possible */
2976         parms.ov_start_sector = mdev->ov_start_sector;
2977         parms.ov_stop_sector = ULLONG_MAX;
2978         if (info->attrs[DRBD_NLA_START_OV_PARMS]) {
2979                 int err = start_ov_parms_from_attrs(&parms, info);
2980                 if (err) {
2981                         retcode = ERR_MANDATORY_TAG;
2982                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2983                         goto out;
2984                 }
2985         }
2986         /* w_make_ov_request expects position to be aligned */
2987         mdev->ov_start_sector = parms.ov_start_sector & ~(BM_SECT_PER_BIT-1);
2988         mdev->ov_stop_sector = parms.ov_stop_sector;
2989
2990         /* If there is still bitmap IO pending, e.g. previous resync or verify
2991          * just being finished, wait for it before requesting a new resync. */
2992         drbd_suspend_io(mdev);
2993         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2994         retcode = drbd_request_state(mdev,NS(conn,C_VERIFY_S));
2995         drbd_resume_io(mdev);
2996 out:
2997         drbd_adm_finish(info, retcode);
2998         return 0;
2999 }
3000
3001
3002 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info)
3003 {
3004         struct drbd_conf *mdev;
3005         enum drbd_ret_code retcode;
3006         int skip_initial_sync = 0;
3007         int err;
3008         struct new_c_uuid_parms args;
3009
3010         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
3011         if (!adm_ctx.reply_skb)
3012                 return retcode;
3013         if (retcode != NO_ERROR)
3014                 goto out_nolock;
3015
3016         mdev = adm_ctx.mdev;
3017         memset(&args, 0, sizeof(args));
3018         if (info->attrs[DRBD_NLA_NEW_C_UUID_PARMS]) {
3019                 err = new_c_uuid_parms_from_attrs(&args, info);
3020                 if (err) {
3021                         retcode = ERR_MANDATORY_TAG;
3022                         drbd_msg_put_info(from_attrs_err_to_txt(err));
3023                         goto out_nolock;
3024                 }
3025         }
3026
3027         mutex_lock(mdev->state_mutex); /* Protects us against serialized state changes. */
3028
3029         if (!get_ldev(mdev)) {
3030                 retcode = ERR_NO_DISK;
3031                 goto out;
3032         }
3033
3034         /* this is "skip initial sync", assume to be clean */
3035         if (mdev->state.conn == C_CONNECTED && mdev->tconn->agreed_pro_version >= 90 &&
3036             mdev->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED && args.clear_bm) {
3037                 dev_info(DEV, "Preparing to skip initial sync\n");
3038                 skip_initial_sync = 1;
3039         } else if (mdev->state.conn != C_STANDALONE) {
3040                 retcode = ERR_CONNECTED;
3041                 goto out_dec;
3042         }
3043
3044         drbd_uuid_set(mdev, UI_BITMAP, 0); /* Rotate UI_BITMAP to History 1, etc... */
3045         drbd_uuid_new_current(mdev); /* New current, previous to UI_BITMAP */
3046
3047         if (args.clear_bm) {
3048                 err = drbd_bitmap_io(mdev, &drbd_bmio_clear_n_write,
3049                         "clear_n_write from new_c_uuid", BM_LOCKED_MASK);
3050                 if (err) {
3051                         dev_err(DEV, "Writing bitmap failed with %d\n",err);
3052                         retcode = ERR_IO_MD_DISK;
3053                 }
3054                 if (skip_initial_sync) {
3055                         drbd_send_uuids_skip_initial_sync(mdev);
3056                         _drbd_uuid_set(mdev, UI_BITMAP, 0);
3057                         drbd_print_uuids(mdev, "cleared bitmap UUID");
3058                         spin_lock_irq(&mdev->tconn->req_lock);
3059                         _drbd_set_state(_NS2(mdev, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
3060                                         CS_VERBOSE, NULL);
3061                         spin_unlock_irq(&mdev->tconn->req_lock);
3062                 }
3063         }
3064
3065         drbd_md_sync(mdev);
3066 out_dec:
3067         put_ldev(mdev);
3068 out:
3069         mutex_unlock(mdev->state_mutex);
3070 out_nolock:
3071         drbd_adm_finish(info, retcode);
3072         return 0;
3073 }
3074
3075 static enum drbd_ret_code
3076 drbd_check_resource_name(const char *name)
3077 {
3078         if (!name || !name[0]) {
3079                 drbd_msg_put_info("resource name missing");
3080                 return ERR_MANDATORY_TAG;
3081         }
3082         /* if we want to use these in sysfs/configfs/debugfs some day,
3083          * we must not allow slashes */
3084         if (strchr(name, '/')) {
3085                 drbd_msg_put_info("invalid resource name");
3086                 return ERR_INVALID_REQUEST;
3087         }
3088         return NO_ERROR;
3089 }
3090
3091 int drbd_adm_new_resource(struct sk_buff *skb, struct genl_info *info)
3092 {
3093         enum drbd_ret_code retcode;
3094         struct res_opts res_opts;
3095         int err;
3096
3097         retcode = drbd_adm_prepare(skb, info, 0);
3098         if (!adm_ctx.reply_skb)
3099                 return retcode;
3100         if (retcode != NO_ERROR)
3101                 goto out;
3102
3103         set_res_opts_defaults(&res_opts);
3104         err = res_opts_from_attrs(&res_opts, info);
3105         if (err && err != -ENOMSG) {
3106                 retcode = ERR_MANDATORY_TAG;
3107                 drbd_msg_put_info(from_attrs_err_to_txt(err));
3108                 goto out;
3109         }
3110
3111         retcode = drbd_check_resource_name(adm_ctx.resource_name);
3112         if (retcode != NO_ERROR)
3113                 goto out;
3114
3115         if (adm_ctx.tconn) {
3116                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL) {
3117                         retcode = ERR_INVALID_REQUEST;
3118                         drbd_msg_put_info("resource exists");
3119                 }
3120                 /* else: still NO_ERROR */
3121                 goto out;
3122         }
3123
3124         if (!conn_create(adm_ctx.resource_name, &res_opts))
3125                 retcode = ERR_NOMEM;
3126 out:
3127         drbd_adm_finish(info, retcode);
3128         return 0;
3129 }
3130
3131 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info)
3132 {
3133         struct drbd_genlmsghdr *dh = info->userhdr;
3134         enum drbd_ret_code retcode;
3135
3136         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
3137         if (!adm_ctx.reply_skb)
3138                 return retcode;
3139         if (retcode != NO_ERROR)
3140                 goto out;
3141
3142         if (dh->minor > MINORMASK) {
3143                 drbd_msg_put_info("requested minor out of range");
3144                 retcode = ERR_INVALID_REQUEST;
3145                 goto out;
3146         }
3147         if (adm_ctx.volume > DRBD_VOLUME_MAX) {
3148                 drbd_msg_put_info("requested volume id out of range");
3149                 retcode = ERR_INVALID_REQUEST;
3150                 goto out;
3151         }
3152
3153         /* drbd_adm_prepare made sure already
3154          * that mdev->tconn and mdev->vnr match the request. */
3155         if (adm_ctx.mdev) {
3156                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL)
3157                         retcode = ERR_MINOR_EXISTS;
3158                 /* else: still NO_ERROR */
3159                 goto out;
3160         }
3161
3162         retcode = conn_new_minor(adm_ctx.tconn, dh->minor, adm_ctx.volume);
3163 out:
3164         drbd_adm_finish(info, retcode);
3165         return 0;
3166 }
3167
3168 static enum drbd_ret_code adm_delete_minor(struct drbd_conf *mdev)
3169 {
3170         if (mdev->state.disk == D_DISKLESS &&
3171             /* no need to be mdev->state.conn == C_STANDALONE &&
3172              * we may want to delete a minor from a live replication group.
3173              */
3174             mdev->state.role == R_SECONDARY) {
3175                 _drbd_request_state(mdev, NS(conn, C_WF_REPORT_PARAMS),
3176                                     CS_VERBOSE + CS_WAIT_COMPLETE);
3177                 idr_remove(&mdev->tconn->volumes, mdev->vnr);
3178                 idr_remove(&minors, mdev_to_minor(mdev));
3179                 del_gendisk(mdev->vdisk);
3180                 synchronize_rcu();
3181                 kref_put(&mdev->kref, &drbd_minor_destroy);
3182                 return NO_ERROR;
3183         } else
3184                 return ERR_MINOR_CONFIGURED;
3185 }
3186
3187 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info)
3188 {
3189         enum drbd_ret_code retcode;
3190
3191         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
3192         if (!adm_ctx.reply_skb)
3193                 return retcode;
3194         if (retcode != NO_ERROR)
3195                 goto out;
3196
3197         retcode = adm_delete_minor(adm_ctx.mdev);
3198 out:
3199         drbd_adm_finish(info, retcode);
3200         return 0;
3201 }
3202
3203 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info)
3204 {
3205         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
3206         struct drbd_conf *mdev;
3207         unsigned i;
3208
3209         retcode = drbd_adm_prepare(skb, info, 0);
3210         if (!adm_ctx.reply_skb)
3211                 return retcode;
3212         if (retcode != NO_ERROR)
3213                 goto out;
3214
3215         if (!adm_ctx.tconn) {
3216                 retcode = ERR_RES_NOT_KNOWN;
3217                 goto out;
3218         }
3219
3220         /* demote */
3221         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3222                 retcode = drbd_set_role(mdev, R_SECONDARY, 0);
3223                 if (retcode < SS_SUCCESS) {
3224                         drbd_msg_put_info("failed to demote");
3225                         goto out;
3226                 }
3227         }
3228
3229         retcode = conn_try_disconnect(adm_ctx.tconn, 0);
3230         if (retcode < SS_SUCCESS) {
3231                 drbd_msg_put_info("failed to disconnect");
3232                 goto out;
3233         }
3234
3235         /* detach */
3236         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3237                 retcode = adm_detach(mdev, 0);
3238                 if (retcode < SS_SUCCESS || retcode > NO_ERROR) {
3239                         drbd_msg_put_info("failed to detach");
3240                         goto out;
3241                 }
3242         }
3243
3244         /* If we reach this, all volumes (of this tconn) are Secondary,
3245          * Disconnected, Diskless, aka Unconfigured. Make sure all threads have
3246          * actually stopped, state handling only does drbd_thread_stop_nowait(). */
3247         drbd_thread_stop(&adm_ctx.tconn->worker);
3248
3249         /* Now, nothing can fail anymore */
3250
3251         /* delete volumes */
3252         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3253                 retcode = adm_delete_minor(mdev);
3254                 if (retcode != NO_ERROR) {
3255                         /* "can not happen" */
3256                         drbd_msg_put_info("failed to delete volume");
3257                         goto out;
3258                 }
3259         }
3260
3261         /* delete connection */
3262         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3263                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3264                 synchronize_rcu();
3265                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3266
3267                 retcode = NO_ERROR;
3268         } else {
3269                 /* "can not happen" */
3270                 retcode = ERR_RES_IN_USE;
3271                 drbd_msg_put_info("failed to delete connection");
3272         }
3273         goto out;
3274 out:
3275         drbd_adm_finish(info, retcode);
3276         return 0;
3277 }
3278
3279 int drbd_adm_del_resource(struct sk_buff *skb, struct genl_info *info)
3280 {
3281         enum drbd_ret_code retcode;
3282
3283         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
3284         if (!adm_ctx.reply_skb)
3285                 return retcode;
3286         if (retcode != NO_ERROR)
3287                 goto out;
3288
3289         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3290                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3291                 synchronize_rcu();
3292                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3293
3294                 retcode = NO_ERROR;
3295         } else {
3296                 retcode = ERR_RES_IN_USE;
3297         }
3298
3299         if (retcode == NO_ERROR)
3300                 drbd_thread_stop(&adm_ctx.tconn->worker);
3301 out:
3302         drbd_adm_finish(info, retcode);
3303         return 0;
3304 }
3305
3306 void drbd_bcast_event(struct drbd_conf *mdev, const struct sib_info *sib)
3307 {
3308         static atomic_t drbd_genl_seq = ATOMIC_INIT(2); /* two. */
3309         struct sk_buff *msg;
3310         struct drbd_genlmsghdr *d_out;
3311         unsigned seq;
3312         int err = -ENOMEM;
3313
3314         if (sib->sib_reason == SIB_SYNC_PROGRESS) {
3315                 if (time_after(jiffies, mdev->rs_last_bcast + HZ))
3316                         mdev->rs_last_bcast = jiffies;
3317                 else
3318                         return;
3319         }
3320
3321         seq = atomic_inc_return(&drbd_genl_seq);
3322         msg = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
3323         if (!msg)
3324                 goto failed;
3325
3326         err = -EMSGSIZE;
3327         d_out = genlmsg_put(msg, 0, seq, &drbd_genl_family, 0, DRBD_EVENT);
3328         if (!d_out) /* cannot happen, but anyways. */
3329                 goto nla_put_failure;
3330         d_out->minor = mdev_to_minor(mdev);
3331         d_out->ret_code = NO_ERROR;
3332
3333         if (nla_put_status_info(msg, mdev, sib))
3334                 goto nla_put_failure;
3335         genlmsg_end(msg, d_out);
3336         err = drbd_genl_multicast_events(msg, 0);
3337         /* msg has been consumed or freed in netlink_broadcast() */
3338         if (err && err != -ESRCH)
3339                 goto failed;
3340
3341         return;
3342
3343 nla_put_failure:
3344         nlmsg_free(msg);
3345 failed:
3346         dev_err(DEV, "Error %d while broadcasting event. "
3347                         "Event seq:%u sib_reason:%u\n",
3348                         err, seq, sib->sib_reason);
3349 }